core

package
v1.1.0-beta.0...-2a72e7f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 25, 2024 License: Apache-2.0 Imports: 142 Imported by: 0

Documentation

Overview

Package core Copyright 2022 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.

Index

Constants

View Source
const (
	// AlterDDLJobThread alter reorg worker count
	AlterDDLJobThread = "thread"
	// AlterDDLJobBatchSize alter reorg batch size
	AlterDDLJobBatchSize = "batch_size"
	// AlterDDLJobMaxWriteSpeed alter reorg max write speed
	AlterDDLJobMaxWriteSpeed = "max_write_speed"
)
View Source
const (
	// ErrExprInSelect  is in select fields for the error of ErrFieldNotInGroupBy
	ErrExprInSelect = "SELECT list"
	// ErrExprInOrderBy  is in order by items for the error of ErrFieldNotInGroupBy
	ErrExprInOrderBy = "ORDER BY"
)
View Source
const (
	TableSchema      = "table_schema"
	TableName        = "table_name"
	TidbTableID      = "tidb_table_id"
	PartitionName    = "partition_name"
	TidbPartitionID  = "tidb_partition_id"
	IndexName        = "index_name"
	SchemaName       = "schema_name"
	DBName           = "db_name"
	ConstraintSchema = "constraint_schema"
	ConstraintName   = "constraint_name"
	TableID          = "table_id"
	SequenceSchema   = "sequence_schema"
	SequenceName     = "sequence_name"
	ColumnName       = "column_name"
	DDLStateName     = "state"
)
View Source
const (
	// HotRegionTypeRead hot read region.
	HotRegionTypeRead = "read"
	// HotRegionTypeWrite hot write region.
	HotRegionTypeWrite = "write"
)
View Source
const (
	// PartitionHashSplitterType is the splitter splits by hash.
	PartitionHashSplitterType = iota
	// PartitionRangeSplitterType is the splitter that split sorted data into the same range
	PartitionRangeSplitterType
)
View Source
const (
	// RowCountLbl indicates for rowCount
	RowCountLbl = "rowCount"
	// RowSizeLbl indicates rowSize
	RowSizeLbl = "rowSize"
	// BuildRowCountLbl indicates rowCount on build side
	BuildRowCountLbl = "buildRowCount"
	// ProbeRowCountLbl indicates rowCount on probe side
	ProbeRowCountLbl = "probeRowCount"
	// NumPairsLbl indicates numPairs
	NumPairsLbl = "numPairs"

	// NetworkFactorLbl indicates networkFactor
	NetworkFactorLbl = "networkFactor"
	// SeekFactorLbl indicates seekFactor
	SeekFactorLbl = "seekFactor"
	// ScanFactorLbl indicates for scanFactor
	ScanFactorLbl = "scanFactor"
	// SelectionFactorLbl indicates selection factor
	SelectionFactorLbl = "selectionFactor"
	// CPUFactorLbl indicates cpu factor
	CPUFactorLbl = "cpuFactor"
	// MemoryFactorLbl indicates mem factor
	MemoryFactorLbl = "memoryFactor"
	// DiskFactorLbl indicates disk factor
	DiskFactorLbl = "diskFactor"
	// ConcurrencyFactorLbl indicates for concurrency factor
	ConcurrencyFactorLbl = "concurrencyFactor"

	// ScanConcurrencyLbl indicates sql scan concurrency
	ScanConcurrencyLbl = "scanConcurrency"
	// HashJoinConcurrencyLbl indicates concurrency for hash join
	HashJoinConcurrencyLbl = "hashJoinConcurrency"

	// NetSeekCostLbl indicates netSeek cost
	NetSeekCostLbl = "netSeekCost"
	// TablePlanCostLbl indicates tablePlan cost
	TablePlanCostLbl = "tablePlanCost"
	// IndexPlanCostLbl indicates indexPlan cost
	IndexPlanCostLbl = "indexPlanCost"

	// ProbeCostDetailLbl indicates probeCost
	ProbeCostDetailLbl = "probeCostDetail"
	// ProbeCostDescLbl indicates description for probe cost
	ProbeCostDescLbl = "probeCostDesc"
	// CPUCostDetailLbl indicates cpuCost detail
	CPUCostDetailLbl = "cpuCostDetail"
	// CPUCostDescLbl indicates description for cpu cost
	CPUCostDescLbl = "cpuCostDesc"
	// MemCostDetailLbl indicates mem cost detail
	MemCostDetailLbl = "memCostDetail"
	// MemCostDescLbl indicates description for mem cost
	MemCostDescLbl = "memCostDesc"
	// DiskCostDetailLbl indicates disk cost detail
	DiskCostDetailLbl = "diskCostDetail"
	// DiskCostDescLbl indicates description for disk cost
	DiskCostDescLbl = "diskCostDesc"
	// ProbeDiskCostLbl indicates probe disk cost detail
	ProbeDiskCostLbl = "probeDiskCostDetail"
	// ProbeDiskCostDescLbl indicates description for probe disk cost
	ProbeDiskCostDescLbl = "probeDiskCostDesc"

	// MemQuotaLbl indicates memory quota
	MemQuotaLbl = "memQuota"
)
View Source
const (
	// MinNumRows provides a minimum to avoid underestimation. As selectivity estimation approaches
	// zero, all plan choices result in a low cost - making it difficult to differentiate plan choices.
	// A low value of 1.0 here is used for most (non probe acceses) to reduce this risk.
	MinNumRows = 1.0
	// MinRowSize provides a minimum column length to ensure that any adjustment or calculation
	// in costing does not go below this value. 2.0 is used as a reasonable lowest column length.
	MinRowSize = 2.0
	// TiFlashStartupRowPenalty applies a startup penalty for TiFlash scan to encourage TiKV usage for small scans
	TiFlashStartupRowPenalty = 10000
	// MaxPenaltyRowCount applies a penalty for high risk scans
	MaxPenaltyRowCount = 1000
)
View Source
const (
	// TraceFormatRow indicates row tracing format.
	TraceFormatRow = "row"
	// TraceFormatJSON indicates json tracing format.
	TraceFormatJSON = "json"
	// TraceFormatLog indicates log tracing format.
	TraceFormatLog = "log"

	// TracePlanTargetEstimation indicates CE trace target for optimizer trace.
	TracePlanTargetEstimation = "estimation"
	// TracePlanTargetDebug indicates debug trace target for optimizer trace.
	TracePlanTargetDebug = "debug"
)
View Source
const (
	// TypeInvalid for unexpected types.
	TypeInvalid byte = iota
	// TypeSelect for SelectStmt.
	TypeSelect
	// TypeSetOpr for SetOprStmt.
	TypeSetOpr
	// TypeDelete for DeleteStmt.
	TypeDelete
	// TypeUpdate for UpdateStmt.
	TypeUpdate
	// TypeInsert for InsertStmt.
	TypeInsert
	// TypeDrop for DropStmt
	TypeDrop
	// TypeCreate for CreateStmt
	TypeCreate
	// TypeAlter for AlterStmt
	TypeAlter
	// TypeRename for RenameStmt
	TypeRename
	// TypeRepair for RepairStmt
	TypeRepair
	// TypeShow for ShowStmt
	TypeShow
	// TypeExecute for ExecuteStmt
	TypeExecute
	// TypeImportInto for ImportIntoStmt
	TypeImportInto
)
View Source
const FullRange = -1

FullRange represent used all partitions.

View Source
const GlobalWithoutColumnPos = -1

GlobalWithoutColumnPos marks the index has no partition column.

View Source
const (
	// MaxCacheableLimitCount is the max limit count for cacheable query.
	MaxCacheableLimitCount = 10000
)
View Source
const PointPlanKey = stringutil.StringerStr("pointPlanKey")

PointPlanKey is used to get point plan that is pre-built for multi-statement query.

Variables

View Source
var AllowCartesianProduct = atomic.NewBool(true)

AllowCartesianProduct means whether tidb allows cartesian join without equal conditions.

View Source
var CMSketchSizeLimit = kv.TxnEntrySizeLimit.Load() / binary.MaxVarintLen32

CMSketchSizeLimit indicates the size limit of CMSketch.

View Source
var DefaultDisabledLogicalRulesList *atomic.Value

DefaultDisabledLogicalRulesList indicates the logical rules which should be banned.

View Source
var EvalSubqueryFirstRow func(ctx context.Context, p base.PhysicalPlan, is infoschema.InfoSchema, sctx base.PlanContext) (row []types.Datum, err error)

EvalSubqueryFirstRow evaluates incorrelated subqueries once, and get first row.

View Source
var GenPlanCostTrace func(p base.PhysicalPlan, costV *costusage.CostVer2, taskType property.TaskType, option *optimizetrace.PlanCostOption)

GenPlanCostTrace define a hook function to customize the cost calculation.

View Source
var HeavyFunctionNameMap = map[string]struct{}{
	"vec_cosine_distance":        {},
	"vec_l1_distance":            {},
	"vec_l2_distance":            {},
	"vec_negative_inner_product": {},
	"vec_dims":                   {},
	"vec_l2_norm":                {},
}

HeavyFunctionNameMap stores function names that is worth to do HeavyFunctionOptimize. Currently this only applies to Vector data types and their functions. The HeavyFunctionOptimize eliminate the usage of the function in TopN operators to avoid vector distance re-calculation of TopN in the root task.

View Source
var (

	// ImportIntoDataSource used inplannererrors.ErrLoadDataInvalidURI.
	ImportIntoDataSource = "data source"
)
View Source
var IsReadOnly func(node ast.Node, vars *variable.SessionVars) bool

IsReadOnly check whether the ast.Node is a read only statement.

OptimizeAstNode optimizes the query to a physical plan directly.

View Source
var PlanCounterDisabled base.PlanCounterTp = -1

PlanCounterDisabled is the default value of PlanCounterTp, indicating that optimizer needn't force a plan.

View Source
var (
	// PreparedPlanCacheMaxMemory stores the max memory size defined in the global config "performance-server-memory-quota".
	PreparedPlanCacheMaxMemory = *atomic2.NewUint64(math.MaxUint64)
)

Functions

func AddExtraPhysTblIDColumn

func AddExtraPhysTblIDColumn(sctx base.PlanContext, columns []*model.ColumnInfo, schema *expression.Schema) ([]*model.ColumnInfo, *expression.Schema, bool)

AddExtraPhysTblIDColumn for partition table. For keepOrder with partition table, we need use partitionHandle to distinct two handles, the `_tidb_rowid` in different partitions can have the same value.

func AllocMPPQueryID

func AllocMPPQueryID() uint64

AllocMPPQueryID allocates local query id for mpp queries.

func AllocMPPTaskID

func AllocMPPTaskID(ctx sessionctx.Context) int64

AllocMPPTaskID allocates task id for mpp tasks. It will reset the task id when the query finished.

func AsSctx

func AsSctx(pctx base.PlanContext) (sessionctx.Context, error)

AsSctx converts PlanContext to sessionctx.Context.

func BinaryPlanStrFromFlatPlan

func BinaryPlanStrFromFlatPlan(explainCtx base.PlanContext, flat *FlatPhysicalPlan) string

BinaryPlanStrFromFlatPlan generates the compressed and encoded binary plan from a FlatPhysicalPlan.

func BuildHandleColsForAnalyze

func BuildHandleColsForAnalyze(ctx base.PlanContext, tblInfo *model.TableInfo, allColumns bool, colsInfo []*model.ColumnInfo) util.HandleCols

BuildHandleColsForAnalyze returns HandleCols for ANALYZE.

func BuildLogicalPlanForTest

func BuildLogicalPlanForTest(ctx context.Context, sctx sessionctx.Context, node *resolve.NodeW, infoSchema infoschema.InfoSchema) (base.Plan, error)

BuildLogicalPlanForTest builds a logical plan for testing purpose from ast.Node.

func BuildPhysicalJoinSchema

func BuildPhysicalJoinSchema(joinType logicalop.JoinType, join base.PhysicalPlan) *expression.Schema

BuildPhysicalJoinSchema builds the schema of PhysicalJoin from it's children's schema.

func Cacheable

func Cacheable(node ast.Node, is infoschema.InfoSchema) bool

Cacheable checks whether the input ast(query) is cacheable with empty session context, which is mainly for testing. TODO: only for test, remove this function later on.

func CacheableWithCtx

func CacheableWithCtx(sctx base.PlanContext, node ast.Node, is infoschema.InfoSchema) (bool, string)

CacheableWithCtx checks whether the input ast(query) is cacheable. TODO: only for test, remove this function later on.

func CheckAggCanPushCop

func CheckAggCanPushCop(sctx base.PlanContext, aggFuncs []*aggregation.AggFuncDesc, groupByItems []expression.Expression, storeType kv.StoreType) bool

CheckAggCanPushCop checks whether the aggFuncs and groupByItems can be pushed down to coprocessor.

func CheckCanConvertAggToProj

func CheckCanConvertAggToProj(agg *logicalop.LogicalAggregation) bool

CheckCanConvertAggToProj check whether a special old aggregation (which has already been pushed down) to projection. link: issue#44795

func CheckParamTypeInt64orUint64

func CheckParamTypeInt64orUint64(param *driver.ParamMarkerExpr) (bool, uint64)

CheckParamTypeInt64orUint64 check param type for plan cache limit, only allow int64 and uint64 now eg: set @a = 1;

func CheckPrivilege

func CheckPrivilege(activeRoles []*auth.RoleIdentity, pm privilege.Manager, vs []visitInfo) error

CheckPrivilege checks the privilege for a user.

func CheckTableLock

func CheckTableLock(ctx tablelock.TableLockReadContext, is infoschema.InfoSchema, vs []visitInfo) error

CheckTableLock checks the table lock.

func CheckUpdateList

func CheckUpdateList(assignFlags []int, updt *Update, newTblID2Table map[int64]table.Table) error

CheckUpdateList checks all related columns in updatable state.

func CollectColumnStatsUsage

func CollectColumnStatsUsage(lp base.LogicalPlan, histNeeded bool) (
	map[model.TableItemID]bool,
	*intset.FastIntSet,
	map[int64][]int64,
)

CollectColumnStatsUsage collects column stats usage from logical plan. predicate indicates whether to collect predicate columns and histNeeded indicates whether to collect histogram-needed columns. The predicate columns are always collected while the histNeeded columns are depending on whether we use sync load. First return value: predicate columns Second return value: the visited table IDs(For partition table, we only record its global meta ID. The meta ID of each partition will be recorded in tblID2PartitionIDs) Third return value: the visited partition IDs. Used for static partition pruning. Forth return value: the recorded asked column group for each datasource table, which will require collecting composite index for it's group ndv info. TODO: remove the third return value when the static partition pruning is totally deprecated.

func CollectDependingVirtualCols

func CollectDependingVirtualCols(tblID2Tbl map[int64]*model.TableInfo, neededItems []model.StatsLoadItem) []model.StatsLoadItem

CollectDependingVirtualCols collects the virtual columns that depend on the needed columns, and returns them in a new slice.

Why do we need this? It's mainly for stats sync loading. Currently, virtual columns themselves don't have statistics. But expression indexes, which are indexes on virtual columns, have statistics. We need to collect needed virtual columns, then needed expression index stats can be collected for sync loading. In normal cases, if a virtual column can be used, which means related statistics may be needed, the corresponding expressions in the query must have already been replaced with the virtual column before here. So we just need to treat them like normal columns in stats sync loading, which means we just extract the Column from the expressions, the virtual columns we want will be there. However, in some cases (the mv index case now), the expressions are not replaced with the virtual columns before here. Instead, we match the expression in the query against the expression behind the virtual columns after here when building the access paths. This means we are unable to known what virtual columns will be needed by just extracting the Column from the expressions here. So we need to manually collect the virtual columns that may be needed.

Note 1: As long as a virtual column depends on the needed columns, it will be collected. This could collect some virtual columns that are not actually needed. It's OK because that's how sync loading is expected. Sync loading only needs to ensure all actually needed stats are triggered to be loaded. Other logic of sync loading also works like this. If we want to collect only the virtual columns that are actually needed, we need to make the checking logic here exactly the same as the logic for generating the access paths, which will make the logic here very complicated.

Note 2: Only direct dependencies are considered here. If a virtual column depends on another virtual column, and the latter depends on the needed columns, then the former will not be collected. For example: create table t(a int, b int, c int as (a+b), d int as (c+1)); If a is needed, then c will be collected, but d will not be collected. It's because currently it's impossible that statistics related to indirectly depending columns are actually needed. If we need to check indirect dependency some day, we can easily extend the logic here.

func CollectFilters4MVIndexMutations

func CollectFilters4MVIndexMutations(sctx base.PlanContext, filters []expression.Expression,
	idxCols []*expression.Column) (accessFilters, remainingFilters []expression.Expression, mvColOffset int, mvFilterMutations []expression.Expression)

CollectFilters4MVIndexMutations exported for unit test. For idx(x, cast(a as array), z), `x=1 and (2 member of a) and (1 member of a) and z=1 and x+z>0` is split to: accessFilters combination: 1: `x=1 and (2 member of a) and z=1`, remaining: `x+z>0`. 2: `x=1 and (1 member of a) and z=1`, remaining: `x+z>0`.

Q: case like idx(x, cast(a as array), z), condition like: x=1 and x=2 and ( 2 member of a)? we can derive the x is invalid range? A: no way to here, it will derive an empty range in table path by all these conditions, and the heuristic rule will pick the table-dual table path directly.

Theoretically For idx(x, cast(a as array), z), `x=1 and x=2 and (2 member of a) and (1 member of a) and z=1 and x+z>0` here should be split to: 1: `x=1 and x=2 and (2 member of a) and z=1`, remaining: `x+z>0`. 2: `x=1 and x=2 and (1 member of a) and z=1`, remaining: `x+z>0`. Note: x=1 and x=2 will derive an invalid range in ranger detach, for now because of heuristic rule above, we ignore this case here.

just as the 3rd point as we said in generateIndexMerge4ComposedIndex

3: The predicate of mv index can not converge to a linear interval range at physical phase like EQ and GT in normal index. Among the predicates in mv index (member-of/contains/overlap), multi conditions about them should be built as self-independent index path, deriving the final intersection/union handles, which means a mv index path may be reused for multi related conditions. Here means whether (2 member of a) And (1 member of a) is valid composed range or empty range can't be told until runtime intersection/union.

therefore, for multi condition about a single mv index virtual json col here: (2 member of a) and (1 member of a) we should build indexMerge above them, and each of them can access to the same mv index. That's why we should derive the mutations of virtual json col's access condition, output the accessFilter combination for each mutation of it.

In the first case: the inputs will be:

filters:[x=1, (2 member of a), (1 member of a), z=1, x+z>0], idxCols: [x,a,z]

the output will be:

accessFilters: [x=1, (2 member of a), z=1], remainingFilters: [x+z>0], mvColOffset: 1, mvFilterMutations[(2 member of a), (1 member of a)]

the outer usage will be: accessFilter[mvColOffset] = each element of mvFilterMutations to get the mv access filters mutation combination.

func CollectPlanStatsVersion

func CollectPlanStatsVersion(plan base.PhysicalPlan, statsInfos map[string]uint64) map[string]uint64

CollectPlanStatsVersion uses to collect the statistics version of the plan.

func ContainHeavyFunction

func ContainHeavyFunction(expr expression.Expression) bool

ContainHeavyFunction check if the expr contains a function that need to do HeavyFunctionOptimize. Currently this only applies to Vector data types and their functions. The HeavyFunctionOptimize eliminate the usage of the function in TopN operators to avoid vector distance re-calculation of TopN in the root task.

func ConvertAggToProj

func ConvertAggToProj(agg *logicalop.LogicalAggregation, schema *expression.Schema) (bool, *logicalop.LogicalProjection)

ConvertAggToProj convert aggregation to projection.

func DebugTraceBestBinding

func DebugTraceBestBinding(s planctx.PlanContext, binding *hint.HintsSet)

DebugTraceBestBinding records the chosen hint to the debug trace.

func DebugTraceReceivedCommand

func DebugTraceReceivedCommand(s base.PlanContext, cmd byte, stmtNode ast.StmtNode)

DebugTraceReceivedCommand records the received command from the client to the debug trace.

func DebugTraceTryBinding

func DebugTraceTryBinding(s planctx.PlanContext, binding *hint.HintsSet)

DebugTraceTryBinding records the hint that might be chosen to the debug trace.

func DoOptimize

func DoOptimize(
	ctx context.Context,
	sctx base.PlanContext,
	flag uint64,
	logic base.LogicalPlan,
) (base.PhysicalPlan, float64, error)

DoOptimize optimizes a logical plan to a physical plan.

func EncodeFlatPlan

func EncodeFlatPlan(flat *FlatPhysicalPlan) string

EncodeFlatPlan encodes a FlatPhysicalPlan with compression.

func EncodePlan

func EncodePlan(p base.Plan) string

EncodePlan is used to encodePlan the plan to the plan tree with compressing. Deprecated: FlattenPhysicalPlan() + EncodeFlatPlan() is preferred.

func EncodeUniqueIndexKey

func EncodeUniqueIndexKey(ctx sessionctx.Context, tblInfo *model.TableInfo, idxInfo *model.IndexInfo, idxVals []types.Datum, tID int64) (_ []byte, err error)

EncodeUniqueIndexKey encodes a unique index key.

func EncodeUniqueIndexValuesForKey

func EncodeUniqueIndexValuesForKey(ctx sessionctx.Context, tblInfo *model.TableInfo, idxInfo *model.IndexInfo, idxVals []types.Datum) (_ []byte, err error)

EncodeUniqueIndexValuesForKey encodes unique index values for a key.

func EraseLastSemicolon

func EraseLastSemicolon(stmt ast.StmtNode)

EraseLastSemicolon removes last semicolon of sql.

func EraseLastSemicolonInSQL

func EraseLastSemicolonInSQL(sql string) string

EraseLastSemicolonInSQL removes last semicolon of the SQL.

func ExpandVirtualColumn

func ExpandVirtualColumn(columns []*model.ColumnInfo, schema *expression.Schema,
	colsInfo []*model.ColumnInfo) []*model.ColumnInfo

ExpandVirtualColumn expands the virtual column's dependent columns to ts's schema and column.

func ExtractOuterApplyCorrelatedCols

func ExtractOuterApplyCorrelatedCols(p base.PhysicalPlan) []*expression.CorrelatedColumn

ExtractOuterApplyCorrelatedCols only extract the correlated columns whose corresponding Apply operator is outside the plan. For Plan-1, ExtractOuterApplyCorrelatedCols(CTE-1) will return cor_col_1. Plan-1:

Apply_1
 |_ outerSide
 |_CTEExec(CTE-1)

CTE-1
 |_Selection(cor_col_1)

For Plan-2, the result of ExtractOuterApplyCorrelatedCols(CTE-2) will not return cor_col_3. Because Apply_3 is inside CTE-2. Plan-2:

Apply_2
 |_ outerSide
 |_ Selection(cor_col_2)
     |_CTEExec(CTE-2)
CTE-2
 |_ Apply_3
     |_ outerSide
     |_ innerSide(cor_col_3)

func ExtractTableList

func ExtractTableList(node *resolve.NodeW, asName bool) []*ast.TableName

ExtractTableList is a wrapper for tableListExtractor and removes duplicate TableName If asName is true, extract AsName prior to OrigName. Privilege check should use OrigName, while expression may use AsName.

func FDToString

func FDToString(p base.LogicalPlan) string

FDToString explains fd transfer over a Plan, returns description string.

func FindColumnInfoByID

func FindColumnInfoByID(colInfos []*model.ColumnInfo, id int64) *model.ColumnInfo

FindColumnInfoByID finds ColumnInfo in cols by ID.

func FindPredicateType

func FindPredicateType(bc base.PlanContext, expr expression.Expression) (*expression.Column, predicateType)

FindPredicateType determines the type of predicate represented by a given expression. It analyzes the provided expression and returns a column (if applicable) and a corresponding predicate type. The function handles different expression types, including constants, scalar functions, and their specific cases: - Logical operators (`OR` and `AND`). - Comparison operators (`EQ`, `NE`, `LT`, `GT`, `LE`, `GE`). - IN predicates with a list of constants. If the expression doesn't match any of these recognized patterns, it returns an `otherPredicate` type.

func GenHintsFromFlatPlan

func GenHintsFromFlatPlan(flat *FlatPhysicalPlan) []*ast.TableOptimizerHint

GenHintsFromFlatPlan generates hints from a FlatPhysicalPlan.

func GenHintsFromPhysicalPlan

func GenHintsFromPhysicalPlan(p base.Plan) []*ast.TableOptimizerHint

GenHintsFromPhysicalPlan generates hints from physical plan.

func GetDBTableInfo

func GetDBTableInfo(visitInfo []visitInfo) []stmtctx.TableEntry

GetDBTableInfo gets the accessed dbs and tables info.

func GetDupAgnosticAggCols

func GetDupAgnosticAggCols(
	p base.LogicalPlan,
	oldAggCols []*expression.Column,
) (isAgg bool, newAggCols []*expression.Column)

GetDupAgnosticAggCols checks whether a base.LogicalPlan is LogicalAggregation. It extracts all the columns from the duplicate agnostic aggregate functions. The returned column set is nil if not all the aggregate functions are duplicate agnostic. Only the following functions are considered to be duplicate agnostic:

  1. MAX(arg)
  2. MIN(arg)
  3. FIRST_ROW(arg)
  4. Other agg functions with DISTINCT flag, like SUM(DISTINCT arg)

func GetExplainAnalyzeRowsForPlan

func GetExplainAnalyzeRowsForPlan(plan *Explain) (rows [][]string)

GetExplainAnalyzeRowsForPlan get explain rows for plan.

func GetExplainRowsForPlan

func GetExplainRowsForPlan(plan base.Plan) (rows [][]string)

GetExplainRowsForPlan get explain rows for plan.

func GetMaxWriteSpeedFromExpression

func GetMaxWriteSpeedFromExpression(opt *AlterDDLJobOpt) (maxWriteSpeed int64, err error)

GetMaxWriteSpeedFromExpression gets the numeric value of the max write speed from the expression.

func GetMergeJoin

func GetMergeJoin(p *logicalop.LogicalJoin, prop *property.PhysicalProperty, schema *expression.Schema, statsInfo *property.StatsInfo, leftStatsInfo *property.StatsInfo, rightStatsInfo *property.StatsInfo) []base.PhysicalPlan

GetMergeJoin convert the logical join to physical merge join based on the physical property.

func GetParamSQLFromAST

func GetParamSQLFromAST(stmt ast.StmtNode) (paramSQL string, paramVals []types.Datum, err error)

GetParamSQLFromAST returns the parameterized SQL of this AST. NOTICE: this function does not modify the original AST. paramVals are copied from this AST.

func GetPhysicalIDsAndPartitionNames

func GetPhysicalIDsAndPartitionNames(tblInfo *model.TableInfo, partitionNames []pmodel.CIStr) ([]int64, []string, error)

GetPhysicalIDsAndPartitionNames returns physical IDs and names of these partitions.

func GetPlanCost

func GetPlanCost(p base.PhysicalPlan, taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCost returns the cost of this plan.

func GetPlanFromPlanCache

func GetPlanFromPlanCache(ctx context.Context, sctx sessionctx.Context,
	isNonPrepared bool, is infoschema.InfoSchema, stmt *PlanCacheStmt,
	params []expression.Expression) (plan base.Plan, names []*types.FieldName, err error)

GetPlanFromPlanCache is the entry point of Plan Cache. It tries to get a valid cached plan from plan cache. If there is no such a plan, it'll call the optimizer to generate a new one. isNonPrepared indicates whether to use the non-prepared plan cache or the prepared plan cache.

func GetPropByOrderByItems

func GetPropByOrderByItems(items []*util.ByItems) (*property.PhysicalProperty, bool)

GetPropByOrderByItems will check if this sort property can be pushed or not. In order to simplify the problem, we only consider the case that all expression are columns.

func GetPropByOrderByItemsContainScalarFunc

func GetPropByOrderByItemsContainScalarFunc(items []*util.ByItems) (*property.PhysicalProperty, bool, bool)

GetPropByOrderByItemsContainScalarFunc will check if this sort property can be pushed or not. In order to simplify the problem, we only consider the case that all expression are columns or some special scalar functions.

func GetStats4Test

func GetStats4Test(p base.LogicalPlan) *property.StatsInfo

GetStats4Test is a exporter just for test.

func GetStatsInfo

func GetStatsInfo(i any) map[string]uint64

GetStatsInfo gets the statistics info from a physical plan tree. Deprecated: FlattenPhysicalPlan() + GetStatsInfoFromFlatPlan() is preferred.

func GetStatsInfoFromFlatPlan

func GetStatsInfoFromFlatPlan(flat *FlatPhysicalPlan) map[string]uint64

GetStatsInfoFromFlatPlan gets the statistics info from a FlatPhysicalPlan.

func GetThreadOrBatchSizeFromExpression

func GetThreadOrBatchSizeFromExpression(opt *AlterDDLJobOpt) (int64, error)

GetThreadOrBatchSizeFromExpression gets the numeric value of the thread or batch size from the expression.

func GetUpdateColumnsInfo

func GetUpdateColumnsInfo(tblID2Table map[int64]table.Table, tblColPosInfos TblColPosInfoSlice, size int) []*table.Column

GetUpdateColumnsInfo get the update columns info.

func InPrepare

func InPrepare(p *preprocessor)

InPrepare is a PreprocessOpt that indicates preprocess is executing under prepare statement.

func InTxnRetry

func InTxnRetry(p *preprocessor)

InTxnRetry is a PreprocessOpt that indicates preprocess is executing under transaction retry.

func InitTxnContextProvider

func InitTxnContextProvider(p *preprocessor)

InitTxnContextProvider is a PreprocessOpt that indicates preprocess should init transaction's context

func InjectExtraProjection

func InjectExtraProjection(plan base.PhysicalPlan) base.PhysicalPlan

InjectExtraProjection is used to extract the expressions of specific operators into a physical Projection operator and inject the Projection below the operators. Thus we can accelerate the expression evaluation by eager evaluation. This function will be called in two situations: 1. In postOptimize. 2. TiDB can be used as a coprocessor, when a plan tree been pushed down to TiDB, we need to inject extra projections for the plan tree as well.

func InjectProjBelowAgg

func InjectProjBelowAgg(aggPlan base.PhysicalPlan, aggFuncs []*aggregation.AggFuncDesc, groupByItems []expression.Expression) base.PhysicalPlan

InjectProjBelowAgg injects a ProjOperator below AggOperator. So that All scalar functions in aggregation may speed up by vectorized evaluation in the `proj`. If all the args of `aggFuncs`, and all the item of `groupByItems` are columns or constants, we do not need to build the `proj`.

func InjectProjBelowSort

func InjectProjBelowSort(p base.PhysicalPlan, orderByItems []*util.ByItems) base.PhysicalPlan

InjectProjBelowSort extracts the ScalarFunctions of `orderByItems` into a PhysicalProjection and injects it below PhysicalTopN/PhysicalSort. The schema of PhysicalSort and PhysicalTopN are the same as the schema of their children. When a projection is injected as the child of PhysicalSort and PhysicalTopN, some extra columns will be added into the schema of the Projection, thus we need to add another Projection upon them to prune the redundant columns.

func IsASTCacheable

func IsASTCacheable(ctx context.Context, sctx base.PlanContext, node ast.Node, is infoschema.InfoSchema) (bool, string)

IsASTCacheable checks whether the input ast(query) is cacheable. Handle "ignore_plan_cache()" hint If there are multiple hints, only one will take effect

func IsAutoCommitTxn

func IsAutoCommitTxn(vars *variable.SessionVars) bool

IsAutoCommitTxn checks if session is in autocommit mode and not InTxn used for fast plan like point get

func IsColsAllFromOuterTable

func IsColsAllFromOuterTable(cols []*expression.Column, outerUniqueIDs set.Int64Set) bool

IsColsAllFromOuterTable check whether the cols all from outer plan

func IsDefaultExprSameColumn

func IsDefaultExprSameColumn(names types.NameSlice, node ast.ExprNode) bool

IsDefaultExprSameColumn - DEFAULT or col = DEFAULT(col)

func IsPointGetWithPKOrUniqueKeyByAutoCommit

func IsPointGetWithPKOrUniqueKeyByAutoCommit(vars *variable.SessionVars, p base.Plan) bool

IsPointGetWithPKOrUniqueKeyByAutoCommit returns true when meets following conditions:

  1. ctx is auto commit tagged
  2. session is not InTxn
  3. plan is point get by pk, or point get by unique index (no double read)

func IsSafeToReusePointGetExecutor

func IsSafeToReusePointGetExecutor(sctx sessionctx.Context, is infoschema.InfoSchema, stmt *PlanCacheStmt) bool

IsSafeToReusePointGetExecutor checks whether this is a PointGet Plan and safe to reuse its executor.

func JSONToString

func JSONToString(j []*ExplainInfoForEncode) (string, error)

JSONToString convert json to string

func LogicalOptimizeTest

func LogicalOptimizeTest(ctx context.Context, flag uint64, logic base.LogicalPlan) (base.LogicalPlan, error)

LogicalOptimizeTest is just exported for test.

func MatchItems

func MatchItems(p *property.PhysicalProperty, items []*util.ByItems) bool

MatchItems checks if this prop's columns can match by items totally.

func MockContext

func MockContext() *mock.Context

MockContext is only used for plan related tests.

func MockGlobalIndexHashPartitionTable

func MockGlobalIndexHashPartitionTable() *model.TableInfo

MockGlobalIndexHashPartitionTable mocks a hash partition table with global index for test

func MockHashPartitionTable

func MockHashPartitionTable() *model.TableInfo

MockHashPartitionTable mocks a hash partition table for test

func MockListPartitionTable

func MockListPartitionTable() *model.TableInfo

MockListPartitionTable mocks a list partition table for test

func MockNoPKTable

func MockNoPKTable() *model.TableInfo

MockNoPKTable is only used for plan related tests.

func MockPartitionInfoSchema

func MockPartitionInfoSchema(definitions []model.PartitionDefinition) infoschema.InfoSchema

MockPartitionInfoSchema mocks an info schema for partition table.

func MockRangePartitionTable

func MockRangePartitionTable() *model.TableInfo

MockRangePartitionTable mocks a range partition table for test

func MockSignedTable

func MockSignedTable() *model.TableInfo

MockSignedTable is only used for plan related tests.

func MockStateNoneColumnTable

func MockStateNoneColumnTable() *model.TableInfo

MockStateNoneColumnTable is only used for plan related tests.

func MockUnsignedTable

func MockUnsignedTable() *model.TableInfo

MockUnsignedTable is only used for plan related tests.

func MockView

func MockView() *model.TableInfo

MockView is only used for plan related tests.

func NewInstancePlanCache

func NewInstancePlanCache(softMemLimit, hardMemLimit int64) sessionctx.InstancePlanCache

NewInstancePlanCache creates a new instance level plan cache.

func NewPlanCacheKey

func NewPlanCacheKey(sctx sessionctx.Context, stmt *PlanCacheStmt) (key, binding string, cacheable bool, reason string, err error)

NewPlanCacheKey creates the plan cache key for this statement. Note: lastUpdatedSchemaVersion will only be set in the case of rc or for update read in order to differentiate the cache key. In other cases, it will be 0. All information that might affect the plan should be considered in this function.

func NewProjInjector

func NewProjInjector() *projInjector

NewProjInjector builds a projInjector.

func NonPreparedPlanCacheableWithCtx

func NonPreparedPlanCacheableWithCtx(sctx base.PlanContext, node ast.Node, is infoschema.InfoSchema) (ok bool, reason string)

NonPreparedPlanCacheableWithCtx checks whether this SQL is cacheable for non-prepared plan cache.

func NormalizeFlatPlan

func NormalizeFlatPlan(flat *FlatPhysicalPlan) (normalized string, digest *parser.Digest)

NormalizeFlatPlan normalizes a FlatPhysicalPlan and generates plan digest.

func NormalizePlan

func NormalizePlan(p base.Plan) (normalized string, digest *parser.Digest)

NormalizePlan is used to normalize the plan and generate plan digest. Deprecated: FlattenPhysicalPlan() + NormalizeFlatPlan() is preferred.

func OptimizeV1

OptimizeV1 includes: logicalOptimize, physicalOptimize

func OptimizeV2

OptimizeV2 includes: normalization, cascadesOptimize, and physicalOptimize.

func ParameterizeAST

func ParameterizeAST(stmt ast.StmtNode) (paramSQL string, params []*driver.ValueExpr, err error)

ParameterizeAST parameterizes this StmtNode. e.g. `select * from t where a<10 and b<23` --> `select * from t where a<? and b<?`, [10, 23]. NOTICE: this function may modify the input stmt.

func Params2Expressions

func Params2Expressions(params []types.Datum) []expression.Expression

Params2Expressions converts these parameters to an expression list.

func ParseParameterizedSQL

func ParseParameterizedSQL(sctx sessionctx.Context, paramSQL string) (ast.StmtNode, error)

ParseParameterizedSQL parse this parameterized SQL with the specified sctx.

func PartitionPruning

func PartitionPruning(ctx base.PlanContext, tbl table.PartitionedTable, conds []expression.Expression, partitionNames []model.CIStr,
	columns []*expression.Column, names types.NameSlice) ([]int, error)

PartitionPruning finds all used partitions according to query conditions, it will return nil if condition match none of partitions. The return value is a array of the idx in the partition definitions array, use pi.Definitions[idx] to get the partition ID

func PrepareIdxColsAndUnwrapArrayType

func PrepareIdxColsAndUnwrapArrayType(
	tableInfo *model.TableInfo,
	idxInfo *model.IndexInfo,
	tblCols []*expression.Column,
	checkOnly1ArrayTypeCol bool,
) (idxCols []*expression.Column, ok bool)

PrepareIdxColsAndUnwrapArrayType collects columns for an index and returns them as []*expression.Column. If any column of them is an array type, we will use it's underlying FieldType in the returned Column.RetType. If checkOnly1ArrayTypeCol is true, we will check if this index contains only one array type column. If not, it will return (nil, false). This check works as a sanity check for an MV index. Though this function is introduced for MV index, it can also be used for normal index if you pass false to checkOnly1ArrayTypeCol. This function is exported for test.

func Preprocess

func Preprocess(ctx context.Context, sctx sessionctx.Context, node *resolve.NodeW, preprocessOpt ...PreprocessOpt) error

Preprocess resolves table names of the node, and checks some statements' validation. preprocessReturn used to extract the infoschema for the tableName and the timestamp from the asof clause.

func PushedDown

func PushedDown(sel *PhysicalSelection, ts *PhysicalTableScan, selectedConds []expression.Expression, selectedSelectivity float64)

PushedDown is used to push down the selected conditions from PhysicalSelection to PhysicalTableScan. Used in unit test, so it is exported.

func RebuildPlan4CachedPlan

func RebuildPlan4CachedPlan(p base.Plan) (ok bool)

RebuildPlan4CachedPlan will rebuild this plan under current user parameters.

func RecheckCTE

func RecheckCTE(p base.LogicalPlan)

RecheckCTE fills the IsOuterMostCTE field for CTEs. It's a temp solution to before we fully use the Sequence to optimize the CTEs. This func checks whether the CTE is referenced only by the main query or not.

func RecursiveDeriveStats4Test

func RecursiveDeriveStats4Test(p base.LogicalPlan) (*property.StatsInfo, error)

RecursiveDeriveStats4Test is a exporter just for test.

func RemoveUnnecessaryFirstRow

func RemoveUnnecessaryFirstRow(
	sctx base.PlanContext,
	finalGbyItems []expression.Expression,
	partialAggFuncs []*aggregation.AggFuncDesc,
	partialGbyItems []expression.Expression,
	partialSchema *expression.Schema,
	firstRowFuncMap map[*aggregation.AggFuncDesc]*aggregation.AggFuncDesc) []*aggregation.AggFuncDesc

RemoveUnnecessaryFirstRow removes unnecessary FirstRow of the aggregation. This function can be used for both LogicalAggregation and PhysicalAggregation. When the select column is same with the group by key, the column can be removed and gets value from the group by key. e.g select a, count(b) from t group by a; The schema is [firstrow(a), count(b), a]. The column firstrow(a) is unnecessary. Can optimize the schema to [count(b), a] , and change the index to get value.

func ReplaceColumnOfExpr

func ReplaceColumnOfExpr(expr expression.Expression, proj *logicalop.LogicalProjection, schema *expression.Schema) expression.Expression

ReplaceColumnOfExpr replaces column of expression by another LogicalProjection.

func RequestLoadStats

func RequestLoadStats(ctx base.PlanContext, neededHistItems []model.StatsLoadItem, syncWait int64) error

RequestLoadStats send load column/index stats requests to stats handle

func RestoreASTWithParams

func RestoreASTWithParams(stmt ast.StmtNode, params []*driver.ValueExpr) error

RestoreASTWithParams restore this parameterized AST with specific parameters. e.g. `select * from t where a<? and b<?`, [10, 23] --> `select * from t where a<10 and b<23`.

func RuntimeFilterListToPB

func RuntimeFilterListToPB(ctx *base.BuildPBContext, runtimeFilterList []*RuntimeFilter, client kv.Client) ([]*tipb.RuntimeFilter, error)

RuntimeFilterListToPB convert runtime filter list to PB list

func SafeClone

func SafeClone(sctx base.PlanContext, v base.PhysicalPlan) (_ base.PhysicalPlan, err error)

SafeClone clones this op.PhysicalPlan and handles its panic.

func SetParameterValuesIntoSCtx

func SetParameterValuesIntoSCtx(sctx base.PlanContext, isNonPrep bool, markers []ast.ParamMarkerExpr, params []expression.Expression) error

SetParameterValuesIntoSCtx sets these parameters into session context.

func SplitSelCondsWithVirtualColumn

func SplitSelCondsWithVirtualColumn(conds []expression.Expression) (withoutVirt []expression.Expression, withVirt []expression.Expression)

SplitSelCondsWithVirtualColumn filter the select conditions which contain virtual column

func SubstituteExpression

func SubstituteExpression(cond expression.Expression, lp base.LogicalPlan, exprToColumn ExprColumnMap, schema *expression.Schema, opt *optimizetrace.LogicalOptimizeOp) bool

SubstituteExpression is Exported for bench

func SyncWaitStatsLoad

func SyncWaitStatsLoad(plan base.LogicalPlan) error

SyncWaitStatsLoad sync-wait for stats load until timeout

func ToString

func ToString(p base.Plan) string

ToString explains a Plan, returns description string.

func TryAddExtraLimit

func TryAddExtraLimit(ctx sessionctx.Context, node ast.StmtNode) ast.StmtNode

TryAddExtraLimit trys to add an extra limit for SELECT or UNION statement when sql_select_limit is set.

func TryFastPlan

func TryFastPlan(ctx base.PlanContext, node *resolve.NodeW) (p base.Plan)

TryFastPlan tries to use the PointGetPlan for the query.

func TurnNominalSortIntoProj

func TurnNominalSortIntoProj(p base.PhysicalPlan, onlyColumn bool, orderByItems []*util.ByItems) base.PhysicalPlan

TurnNominalSortIntoProj will turn nominal sort into two projections. This is to check if the scalar functions will overflow.

func VisitInfo4PrivCheck

func VisitInfo4PrivCheck(ctx context.Context, is infoschema.InfoSchema, node ast.Node, vs []visitInfo) (privVisitInfo []visitInfo)

VisitInfo4PrivCheck generates privilege check infos because privilege check of local temporary tables is different with normal tables. `CREATE` statement needs `CREATE TEMPORARY TABLE` privilege from the database, and subsequent statements do not need any privileges.

Types

type AdminPlugins

type AdminPlugins struct {
	Action  AdminPluginsAction
	Plugins []string
	// contains filtered or unexported fields
}

AdminPlugins administrates tidb plugins.

func (*AdminPlugins) MemoryUsage

func (s *AdminPlugins) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*AdminPlugins) OutputNames

func (s *AdminPlugins) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*AdminPlugins) ResolveIndices

func (*AdminPlugins) ResolveIndices() (err error)

func (*AdminPlugins) Schema

func (s *AdminPlugins) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*AdminPlugins) SetOutputNames

func (s *AdminPlugins) SetOutputNames(names types.NameSlice)

func (*AdminPlugins) SetSchema

func (s *AdminPlugins) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type AdminPluginsAction

type AdminPluginsAction int

AdminPluginsAction indicate action will be taken on plugins.

const (
	// Enable indicates enable plugins.
	Enable AdminPluginsAction = iota + 1
	// Disable indicates disable plugins.
	Disable
)

type AdminShowBDRRole

type AdminShowBDRRole struct {
	// contains filtered or unexported fields
}

AdminShowBDRRole represents a show bdr role plan.

func (*AdminShowBDRRole) MemoryUsage

func (s *AdminShowBDRRole) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*AdminShowBDRRole) OutputNames

func (s *AdminShowBDRRole) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*AdminShowBDRRole) ResolveIndices

func (*AdminShowBDRRole) ResolveIndices() (err error)

func (*AdminShowBDRRole) Schema

func (s *AdminShowBDRRole) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*AdminShowBDRRole) SetOutputNames

func (s *AdminShowBDRRole) SetOutputNames(names types.NameSlice)

func (*AdminShowBDRRole) SetSchema

func (s *AdminShowBDRRole) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type AggInfo

type AggInfo struct {
	AggFuncs     []*aggregation.AggFuncDesc
	GroupByItems []expression.Expression
	Schema       *expression.Schema
}

AggInfo stores the information of an Aggregation.

func BuildFinalModeAggregation

func BuildFinalModeAggregation(
	sctx base.PlanContext, original *AggInfo, partialIsCop bool, isMPPTask bool) (partial, final *AggInfo, firstRowFuncMap map[*aggregation.AggFuncDesc]*aggregation.AggFuncDesc)

BuildFinalModeAggregation splits either LogicalAggregation or PhysicalAggregation to finalAgg and partial1Agg, returns the information of partial and final agg. partialIsCop means whether partial agg is a cop task. When partialIsCop is false, we do not set the AggMode for partialAgg cause it may be split further when building the aggregate executor(e.g. buildHashAgg will split the AggDesc further for parallel executing). firstRowFuncMap is a map between partial first_row to final first_row, will be used in RemoveUnnecessaryFirstRow

type AggMppRunMode

type AggMppRunMode int

AggMppRunMode defines the running mode of aggregation in MPP

const (
	// NoMpp means the default value which does not run in MPP
	NoMpp AggMppRunMode = iota
	// Mpp1Phase runs only 1 phase but requires its child's partition property
	Mpp1Phase
	// Mpp2Phase runs partial agg + final agg with hash partition
	Mpp2Phase
	// MppTiDB runs agg on TiDB (and a partial agg on TiFlash if in 2 phase agg)
	MppTiDB
	// MppScalar also has 2 phases. The second phase runs in a single task.
	MppScalar
)

type AggregateFuncExtractor

type AggregateFuncExtractor struct {

	// AggFuncs is the collected AggregateFuncExprs.
	AggFuncs []*ast.AggregateFuncExpr
	// contains filtered or unexported fields
}

AggregateFuncExtractor visits Expr tree. It collects AggregateFuncExpr from AST Node.

func (*AggregateFuncExtractor) Enter

func (*AggregateFuncExtractor) Enter(n ast.Node) (ast.Node, bool)

Enter implements Visitor interface.

func (*AggregateFuncExtractor) Leave

func (a *AggregateFuncExtractor) Leave(n ast.Node) (ast.Node, bool)

Leave implements Visitor interface.

type AggregationEliminator

type AggregationEliminator struct {
	// contains filtered or unexported fields
}

AggregationEliminator is used to eliminate aggregation grouped by unique key.

func (*AggregationEliminator) Name

func (*AggregationEliminator) Name() string

Name implements the base.LogicalOptRule.<1st> interface.

func (*AggregationEliminator) Optimize

Optimize implements the base.LogicalOptRule.<0th> interface.

type AggregationPushDownSolver

type AggregationPushDownSolver struct {
	// contains filtered or unexported fields
}

AggregationPushDownSolver is a rule that pushes down aggregation functions to the child of LogicalJoin.

func (*AggregationPushDownSolver) Name

Name implements the base.LogicalOptRule.<1st> interface.

func (*AggregationPushDownSolver) Optimize

Optimize implements the base.LogicalOptRule.<0th> interface.

type AlterDDLJob

type AlterDDLJob struct {
	JobID   int64
	Options []*AlterDDLJobOpt
	// contains filtered or unexported fields
}

AlterDDLJob is the plan of admin alter ddl job

func (*AlterDDLJob) MemoryUsage

func (s *AlterDDLJob) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*AlterDDLJob) OutputNames

func (s *AlterDDLJob) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*AlterDDLJob) ResolveIndices

func (*AlterDDLJob) ResolveIndices() (err error)

func (*AlterDDLJob) Schema

func (s *AlterDDLJob) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*AlterDDLJob) SetOutputNames

func (s *AlterDDLJob) SetOutputNames(names types.NameSlice)

func (*AlterDDLJob) SetSchema

func (s *AlterDDLJob) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type AlterDDLJobOpt

type AlterDDLJobOpt struct {
	Name  string
	Value expression.Expression
}

AlterDDLJobOpt represents alter ddl job option.

type Analyze

type Analyze struct {
	ColTasks []AnalyzeColumnsTask
	IdxTasks []AnalyzeIndexTask
	Opts     map[ast.AnalyzeOptionType]uint64
	// OptionsMap is used to store the options for each partition.
	OptionsMap map[int64]V2AnalyzeOptions
	// contains filtered or unexported fields
}

Analyze represents an analyze plan

func (*Analyze) MemoryUsage

func (s *Analyze) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*Analyze) OutputNames

func (s *Analyze) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Analyze) ResolveIndices

func (*Analyze) ResolveIndices() (err error)

func (*Analyze) Schema

func (s *Analyze) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Analyze) SetOutputNames

func (s *Analyze) SetOutputNames(names types.NameSlice)

func (*Analyze) SetSchema

func (s *Analyze) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type AnalyzeColumnsTask

type AnalyzeColumnsTask struct {
	HandleCols       util.HandleCols
	CommonHandleInfo *model.IndexInfo
	ColsInfo         []*model.ColumnInfo
	SkipColsInfo     []*model.ColumnInfo
	TblInfo          *model.TableInfo
	Indexes          []*model.IndexInfo
	AnalyzeInfo
}

AnalyzeColumnsTask is used for analyze columns.

type AnalyzeIndexTask

type AnalyzeIndexTask struct {
	IndexInfo *model.IndexInfo
	TblInfo   *model.TableInfo
	AnalyzeInfo
}

AnalyzeIndexTask is used for analyze index.

type AnalyzeInfo

type AnalyzeInfo struct {
	DBName        string
	TableName     string
	PartitionName string
	TableID       statistics.AnalyzeTableID
	StatsVersion  int
	V2Options     *V2AnalyzeOptions
}

AnalyzeInfo is used to store the database name, table name and partition name of analyze task.

type BatchPointGetPlan

type BatchPointGetPlan struct {

	// explicit partition selection
	PartitionNames []pmodel.CIStr `plan-cache-clone:"shallow"`

	TblInfo          *model.TableInfo `plan-cache-clone:"shallow"`
	IndexInfo        *model.IndexInfo `plan-cache-clone:"shallow"`
	Handles          []kv.Handle
	HandleType       *types.FieldType       `plan-cache-clone:"shallow"`
	HandleParams     []*expression.Constant // record all Parameters for Plan-Cache
	IndexValues      [][]types.Datum
	IndexValueParams [][]*expression.Constant // record all Parameters for Plan-Cache
	IndexColTypes    []*types.FieldType       `plan-cache-clone:"shallow"`
	AccessConditions []expression.Expression
	IdxCols          []*expression.Column
	IdxColLens       []int
	// Offset to column used for handle
	HandleColOffset int
	// Static prune mode converted to BatchPointGet
	SinglePartition bool
	// pre-calculated partition definition indexes
	// for Handles or IndexValues
	PartitionIdxs []int
	KeepOrder     bool
	Desc          bool
	Lock          bool
	LockWaitTime  int64
	Columns       []*model.ColumnInfo `plan-cache-clone:"shallow"`
	// contains filtered or unexported fields
}

BatchPointGetPlan represents a physical plan which contains a bunch of keys reference the same table and use the same `unique key`

func (*BatchPointGetPlan) AccessObject

func (p *BatchPointGetPlan) AccessObject() base.AccessObject

AccessObject implements physicalScan interface.

func (*BatchPointGetPlan) AppendChildCandidate

func (*BatchPointGetPlan) AppendChildCandidate(_ *optimizetrace.PhysicalOptimizeOp)

AppendChildCandidate implements PhysicalPlan interface.

func (*BatchPointGetPlan) Attach2Task

func (*BatchPointGetPlan) Attach2Task(...base.Task) base.Task

Attach2Task makes the current physical plan as the father of task's physicalPlan and updates the cost of current task. If the child's task is cop task, some operator may close this task and return a new rootTask.

func (*BatchPointGetPlan) Children

func (*BatchPointGetPlan) Children() []base.PhysicalPlan

Children gets all the children.

func (*BatchPointGetPlan) Clone

Clone implements PhysicalPlan interface.

func (*BatchPointGetPlan) CloneForPlanCache

func (op *BatchPointGetPlan) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*BatchPointGetPlan) Cost

func (p *BatchPointGetPlan) Cost() float64

Cost implements PhysicalPlan interface

func (*BatchPointGetPlan) ExplainInfo

func (p *BatchPointGetPlan) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*BatchPointGetPlan) ExplainNormalizedInfo

func (p *BatchPointGetPlan) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*BatchPointGetPlan) ExtractCorrelatedCols

func (*BatchPointGetPlan) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements PhysicalPlan interface.

func (*BatchPointGetPlan) GetActualProbeCnt

func (p *BatchPointGetPlan) GetActualProbeCnt(statsColl *execdetails.RuntimeStatsColl) int64

GetActualProbeCnt implements PhysicalPlan interface.

func (*BatchPointGetPlan) GetAvgRowSize

func (p *BatchPointGetPlan) GetAvgRowSize() float64

GetAvgRowSize return the average row size.

func (*BatchPointGetPlan) GetChildReqProps

func (*BatchPointGetPlan) GetChildReqProps(_ int) *property.PhysicalProperty

GetChildReqProps gets the required property by child index.

func (*BatchPointGetPlan) GetCost

GetCost returns cost of the PointGetPlan.

func (*BatchPointGetPlan) GetEstRowCountForDisplay

func (p *BatchPointGetPlan) GetEstRowCountForDisplay() float64

GetEstRowCountForDisplay implements PhysicalPlan interface.

func (*BatchPointGetPlan) GetPlanCostVer1

func (p *BatchPointGetPlan) GetPlanCostVer1(_ property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*BatchPointGetPlan) GetPlanCostVer2

func (p *BatchPointGetPlan) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is:

func (*BatchPointGetPlan) Init

func (p *BatchPointGetPlan) Init(ctx base.PlanContext, stats *property.StatsInfo, schema *expression.Schema, names []*types.FieldName, offset int) *BatchPointGetPlan

Init initializes BatchPointGetPlan.

func (*BatchPointGetPlan) LoadTableStats

func (p *BatchPointGetPlan) LoadTableStats(ctx sessionctx.Context)

LoadTableStats preloads the stats data for the physical table

func (*BatchPointGetPlan) MemoryUsage

func (p *BatchPointGetPlan) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of BatchPointGetPlan

func (*BatchPointGetPlan) OperatorInfo

func (p *BatchPointGetPlan) OperatorInfo(normalized bool) string

OperatorInfo implements dataAccesser interface.

func (*BatchPointGetPlan) OutputNames

func (p *BatchPointGetPlan) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*BatchPointGetPlan) PrunePartitionsAndValues

func (p *BatchPointGetPlan) PrunePartitionsAndValues(sctx sessionctx.Context) ([]kv.Handle, bool)

PrunePartitionsAndValues will check which partition to use returns: slice of non-duplicated handles (or nil if IndexValues is used) true if no matching partition (TableDual plan can be used)

func (*BatchPointGetPlan) ResolveIndices

func (p *BatchPointGetPlan) ResolveIndices() error

ResolveIndices resolves the indices for columns. After doing this, the columns can evaluate the rows by their indices.

func (*BatchPointGetPlan) Schema

func (s *BatchPointGetPlan) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*BatchPointGetPlan) SetChild

func (*BatchPointGetPlan) SetChild(_ int, _ base.PhysicalPlan)

SetChild sets a specific child for the plan.

func (*BatchPointGetPlan) SetChildren

func (*BatchPointGetPlan) SetChildren(...base.PhysicalPlan)

SetChildren sets the children for the plan.

func (*BatchPointGetPlan) SetCost

func (p *BatchPointGetPlan) SetCost(cost float64)

SetCost implements PhysicalPlan interface

func (*BatchPointGetPlan) SetOutputNames

func (p *BatchPointGetPlan) SetOutputNames(names types.NameSlice)

SetOutputNames sets the outputting name by the given slice.

func (*BatchPointGetPlan) SetProbeParents

func (p *BatchPointGetPlan) SetProbeParents(probeParents []base.PhysicalPlan)

SetProbeParents implements PhysicalPlan interface.

func (*BatchPointGetPlan) SetSchema

func (s *BatchPointGetPlan) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

func (*BatchPointGetPlan) StatsCount

func (p *BatchPointGetPlan) StatsCount() float64

StatsCount will return the RowCount of property.StatsInfo for this plan.

func (*BatchPointGetPlan) StatsInfo

func (p *BatchPointGetPlan) StatsInfo() *property.StatsInfo

StatsInfo will return the StatsInfo of property.StatsInfo for this plan.

func (*BatchPointGetPlan) ToPB

func (*BatchPointGetPlan) ToPB(_ *base.BuildPBContext, _ kv.StoreType) (*tipb.Executor, error)

ToPB converts physical plan to tipb executor.

type CTEDefinition

type CTEDefinition PhysicalCTE

CTEDefinition is CTE definition for explain.

func (*CTEDefinition) ExplainID

func (p *CTEDefinition) ExplainID() fmt.Stringer

ExplainID overrides the ExplainID.

func (*CTEDefinition) ExplainInfo

func (p *CTEDefinition) ExplainInfo() string

ExplainInfo overrides the ExplainInfo

func (*CTEDefinition) MemoryUsage

func (p *CTEDefinition) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of CTEDefinition

type CancelDDLJobs

type CancelDDLJobs struct {
	JobIDs []int64
	// contains filtered or unexported fields
}

CancelDDLJobs represents a cancel DDL jobs plan.

func (*CancelDDLJobs) MemoryUsage

func (s *CancelDDLJobs) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*CancelDDLJobs) OutputNames

func (s *CancelDDLJobs) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*CancelDDLJobs) ResolveIndices

func (*CancelDDLJobs) ResolveIndices() (err error)

func (*CancelDDLJobs) Schema

func (s *CancelDDLJobs) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*CancelDDLJobs) SetOutputNames

func (s *CancelDDLJobs) SetOutputNames(names types.NameSlice)

func (*CancelDDLJobs) SetSchema

func (s *CancelDDLJobs) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type Change

type Change struct {
	*ast.ChangeStmt
	// contains filtered or unexported fields
}

Change represents a change plan.

func (*Change) MemoryUsage

func (s *Change) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*Change) OutputNames

func (s *Change) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Change) ResolveIndices

func (*Change) ResolveIndices() (err error)

func (*Change) Schema

func (s *Change) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Change) SetOutputNames

func (s *Change) SetOutputNames(names types.NameSlice)

func (*Change) SetSchema

func (s *Change) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type CheckIndexRange

type CheckIndexRange struct {
	Table     *ast.TableName
	IndexName string

	HandleRanges []ast.HandleRange
	// contains filtered or unexported fields
}

CheckIndexRange is used for checking index data, output the index values that handle within begin and end.

func (*CheckIndexRange) MemoryUsage

func (s *CheckIndexRange) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*CheckIndexRange) OutputNames

func (s *CheckIndexRange) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*CheckIndexRange) ResolveIndices

func (*CheckIndexRange) ResolveIndices() (err error)

func (*CheckIndexRange) Schema

func (s *CheckIndexRange) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*CheckIndexRange) SetOutputNames

func (s *CheckIndexRange) SetOutputNames(names types.NameSlice)

func (*CheckIndexRange) SetSchema

func (s *CheckIndexRange) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type CheckTable

type CheckTable struct {
	DBName             string
	Table              table.Table
	IndexInfos         []*model.IndexInfo
	IndexLookUpReaders []*PhysicalIndexLookUpReader
	CheckIndex         bool
	// contains filtered or unexported fields
}

CheckTable is used for checking table data, built from the 'admin check table' statement.

func (*CheckTable) MemoryUsage

func (s *CheckTable) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*CheckTable) OutputNames

func (s *CheckTable) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*CheckTable) ResolveIndices

func (*CheckTable) ResolveIndices() (err error)

func (*CheckTable) Schema

func (s *CheckTable) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*CheckTable) SetOutputNames

func (s *CheckTable) SetOutputNames(names types.NameSlice)

func (*CheckTable) SetSchema

func (s *CheckTable) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ChecksumTable

type ChecksumTable struct {
	Tables []*resolve.TableNameW
	// contains filtered or unexported fields
}

ChecksumTable is used for calculating table checksum, built from the `admin checksum table` statement.

func (*ChecksumTable) MemoryUsage

func (s *ChecksumTable) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*ChecksumTable) OutputNames

func (s *ChecksumTable) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*ChecksumTable) ResolveIndices

func (*ChecksumTable) ResolveIndices() (err error)

func (*ChecksumTable) Schema

func (s *ChecksumTable) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*ChecksumTable) SetOutputNames

func (s *ChecksumTable) SetOutputNames(names types.NameSlice)

func (*ChecksumTable) SetSchema

func (s *ChecksumTable) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type CleanupIndex

type CleanupIndex struct {
	Table     *resolve.TableNameW
	IndexName string
	// contains filtered or unexported fields
}

CleanupIndex is used to delete dangling index data.

func (*CleanupIndex) MemoryUsage

func (s *CleanupIndex) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*CleanupIndex) OutputNames

func (s *CleanupIndex) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*CleanupIndex) ResolveIndices

func (*CleanupIndex) ResolveIndices() (err error)

func (*CleanupIndex) Schema

func (s *CleanupIndex) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*CleanupIndex) SetOutputNames

func (s *CleanupIndex) SetOutputNames(names types.NameSlice)

func (*CleanupIndex) SetSchema

func (s *CleanupIndex) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ClusterLogTableExtractor

type ClusterLogTableExtractor struct {

	// SkipRequest means the where clause always false, we don't need to request any component
	SkipRequest bool

	// NodeTypes represents all components types we should send request to.
	// e.g:
	// 1. SELECT * FROM cluster_log WHERE type='tikv'
	// 2. SELECT * FROM cluster_log WHERE type in ('tikv', 'tidb')
	NodeTypes set.StringSet

	// Instances represents all components instances we should send request to.
	// e.g:
	// 1. SELECT * FROM cluster_log WHERE instance='192.168.1.7:2379'
	// 2. SELECT * FROM cluster_log WHERE instance in ('192.168.1.7:2379', '192.168.1.9:2379')
	Instances set.StringSet

	// StartTime represents the beginning time of log message
	// e.g: SELECT * FROM cluster_log WHERE time>'2019-10-10 10:10:10.999'
	StartTime int64
	// EndTime represents the ending time of log message
	// e.g: SELECT * FROM cluster_log WHERE time<'2019-10-11 10:10:10.999'
	EndTime int64
	// Pattern is used to filter the log message
	// e.g:
	// 1. SELECT * FROM cluster_log WHERE message like '%gc%'
	// 2. SELECT * FROM cluster_log WHERE message regexp '.*'
	Patterns  []string
	LogLevels set.StringSet
	// contains filtered or unexported fields
}

ClusterLogTableExtractor is used to extract some predicates of `cluster_config`

func (*ClusterLogTableExtractor) ExplainInfo

func (e *ClusterLogTableExtractor) ExplainInfo(pp base.PhysicalPlan) string

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*ClusterLogTableExtractor) Extract

Extract implements the MemTablePredicateExtractor Extract interface

type ClusterTableExtractor

type ClusterTableExtractor struct {

	// SkipRequest means the where clause always false, we don't need to request any component
	SkipRequest bool

	// NodeTypes represents all components types we should send request to.
	// e.g:
	// 1. SELECT * FROM cluster_config WHERE type='tikv'
	// 2. SELECT * FROM cluster_config WHERE type in ('tikv', 'tidb')
	NodeTypes set.StringSet

	// Instances represents all components instances we should send request to.
	// e.g:
	// 1. SELECT * FROM cluster_config WHERE instance='192.168.1.7:2379'
	// 2. SELECT * FROM cluster_config WHERE type in ('192.168.1.7:2379', '192.168.1.9:2379')
	Instances set.StringSet
	// contains filtered or unexported fields
}

ClusterTableExtractor is used to extract some predicates of cluster table.

func (*ClusterTableExtractor) ExplainInfo

func (e *ClusterTableExtractor) ExplainInfo(_ base.PhysicalPlan) string

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*ClusterTableExtractor) Extract

func (e *ClusterTableExtractor) Extract(ctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) []expression.Expression

Extract implements the MemTablePredicateExtractor Extract interface

type ColWithCmpFuncManager

type ColWithCmpFuncManager struct {
	TargetCol *expression.Column

	OpType []string

	TmpConstant []*expression.Constant
	// contains filtered or unexported fields
}

ColWithCmpFuncManager is used in index join to handle the column with compare functions(>=, >, <, <=). It stores the compare functions and build ranges in execution phase.

func (*ColWithCmpFuncManager) BuildRangesByRow

func (cwc *ColWithCmpFuncManager) BuildRangesByRow(ctx *rangerctx.RangerContext, row chunk.Row) ([]*ranger.Range, error)

BuildRangesByRow will build range of the given row. It will eval each function's arg then call BuildRange.

func (*ColWithCmpFuncManager) CompareRow

func (cwc *ColWithCmpFuncManager) CompareRow(lhs, rhs chunk.Row) int

CompareRow compares the rows for deduplicate.

func (*ColWithCmpFuncManager) MemoryUsage

func (cwc *ColWithCmpFuncManager) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of ColWithCmpFuncManager

func (*ColWithCmpFuncManager) String

func (cwc *ColWithCmpFuncManager) String() string

String implements Stringer interface.

type CollectPredicateColumnsPoint

type CollectPredicateColumnsPoint struct{}

CollectPredicateColumnsPoint collects the columns that are used in the predicates.

func (CollectPredicateColumnsPoint) Name

Name implements the base.LogicalOptRule.<1st> interface.

func (*CollectPredicateColumnsPoint) Optimize

Optimize implements LogicalOptRule.<0th> interface.

type ColumnPruner

type ColumnPruner struct {
}

ColumnPruner is used to prune unnecessary columns.

func (*ColumnPruner) Name

func (*ColumnPruner) Name() string

Name implements base.LogicalOptRule.<1st> interface.

func (*ColumnPruner) Optimize

Optimize implements base.LogicalOptRule.<0th> interface.

type CompactTable

type CompactTable struct {
	ReplicaKind    ast.CompactReplicaKind
	TableInfo      *model.TableInfo
	PartitionNames []pmodel.CIStr
	// contains filtered or unexported fields
}

CompactTable represents a "ALTER TABLE [NAME] COMPACT ..." plan.

func (*CompactTable) MemoryUsage

func (s *CompactTable) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*CompactTable) OutputNames

func (s *CompactTable) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*CompactTable) ResolveIndices

func (*CompactTable) ResolveIndices() (err error)

func (*CompactTable) Schema

func (s *CompactTable) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*CompactTable) SetOutputNames

func (s *CompactTable) SetOutputNames(names types.NameSlice)

func (*CompactTable) SetSchema

func (s *CompactTable) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ConvertOuterToInnerJoin

type ConvertOuterToInnerJoin struct {
}

ConvertOuterToInnerJoin converts outer to inner joins if the unmtaching rows are filtered.

func (*ConvertOuterToInnerJoin) Name

Name implements base.LogicalOptRule.<1st> interface.

func (*ConvertOuterToInnerJoin) Optimize

Optimize implements base.LogicalOptRule.<0th> interface. convertOuterToInnerJoin is refactoring of the outer to inner join logic that used to be part of predicate push down. The rewrite passes down predicates from selection (WHERE clause) and join predicates (ON clause). All nodes except LogicalJoin are pass through where the rewrite is done for the child and nothing for the node itself. The main logic is applied for joins:

  1. Traversal is preorder and the passed down predicate is checked for the left/right after join
  2. The ON clause and passed down predicate (from higher selects or joins) are comined and applied to join children. This logic depends on the join type with the following logic: - For left/right outer joins, the ON clause an be applied only on the inner side (null producing side) - For inner/semi joins, the ON clause can be applied on both children - For anti semi joins, ON clause applied only on left side - For all other cases, do not pass ON clause.

type CopTask

type CopTask struct {
	// contains filtered or unexported fields
}

CopTask is a task that runs in a distributed kv store. TODO: In future, we should split copTask to indexTask and tableTask.

func (*CopTask) ConvertToRootTask

func (t *CopTask) ConvertToRootTask(ctx base.PlanContext) base.Task

ConvertToRootTask implements Task interface.

func (*CopTask) Copy

func (t *CopTask) Copy() base.Task

Copy implements Task interface.

func (*CopTask) Count

func (t *CopTask) Count() float64

Count implements Task interface.

func (*CopTask) Invalid

func (t *CopTask) Invalid() bool

Invalid implements Task interface.

func (*CopTask) MemoryUsage

func (t *CopTask) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of copTask

func (*CopTask) Plan

func (t *CopTask) Plan() base.PhysicalPlan

Plan implements Task interface. copTask plan should be careful with indexMergeReader, whose real plan is stored in idxMergePartPlans, when its indexPlanFinished is marked with false.

type DDL

type DDL struct {
	Statement ast.DDLNode
	// contains filtered or unexported fields
}

DDL represents a DDL statement plan.

func (*DDL) MemoryUsage

func (s *DDL) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*DDL) OutputNames

func (s *DDL) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*DDL) ResolveIndices

func (*DDL) ResolveIndices() (err error)

func (*DDL) Schema

func (s *DDL) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*DDL) SetOutputNames

func (s *DDL) SetOutputNames(names types.NameSlice)

func (*DDL) SetSchema

func (s *DDL) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type Deallocate

type Deallocate struct {
	Name string
	// contains filtered or unexported fields
}

Deallocate represents deallocate plan.

func (*Deallocate) MemoryUsage

func (s *Deallocate) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*Deallocate) OutputNames

func (s *Deallocate) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Deallocate) ResolveIndices

func (*Deallocate) ResolveIndices() (err error)

func (*Deallocate) Schema

func (s *Deallocate) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Deallocate) SetOutputNames

func (s *Deallocate) SetOutputNames(names types.NameSlice)

func (*Deallocate) SetSchema

func (s *Deallocate) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type DecorrelateSolver

type DecorrelateSolver struct{}

DecorrelateSolver tries to convert apply plan to join plan.

func (*DecorrelateSolver) Name

func (*DecorrelateSolver) Name() string

Name implements base.LogicalOptRule.<1st> interface.

func (*DecorrelateSolver) Optimize

Optimize implements base.LogicalOptRule.<0th> interface.

type Delete

type Delete struct {
	IsMultiTable bool

	SelectPlan base.PhysicalPlan

	TblColPosInfos TblColPosInfoSlice `plan-cache-clone:"shallow"`

	FKChecks   map[int64][]*FKCheck   `plan-cache-clone:"must-nil"`
	FKCascades map[int64][]*FKCascade `plan-cache-clone:"must-nil"`

	IgnoreErr bool
	// contains filtered or unexported fields
}

Delete represents a delete plan.

func (*Delete) CloneForPlanCache

func (op *Delete) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (Delete) Init

func (p Delete) Init(ctx base.PlanContext) *Delete

Init initializes Delete.

func (*Delete) MemoryUsage

func (p *Delete) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of Delete

func (*Delete) OutputNames

func (s *Delete) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Delete) ResolveIndices

func (*Delete) ResolveIndices() (err error)

func (*Delete) Schema

func (s *Delete) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Delete) SetOutputNames

func (s *Delete) SetOutputNames(names types.NameSlice)

func (*Delete) SetSchema

func (s *Delete) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type DeriveTopNFromWindow

type DeriveTopNFromWindow struct {
}

DeriveTopNFromWindow pushes down the topN or limit. In the future we will remove the limit from `requiredProperty` in CBO phase.

func (*DeriveTopNFromWindow) Name

func (*DeriveTopNFromWindow) Name() string

Name implements base.LogicalOptRule.<1st> interface.

func (*DeriveTopNFromWindow) Optimize

Optimize implements base.LogicalOptRule.<0th> interface.

type DynamicPartitionAccessObject

type DynamicPartitionAccessObject struct {
	Database      string
	Table         string
	AllPartitions bool
	Partitions    []string
	// contains filtered or unexported fields
}

DynamicPartitionAccessObject represents the partitions accessed by the children of this operator. It's mainly used in dynamic pruning mode.

func (*DynamicPartitionAccessObject) String

type DynamicPartitionAccessObjects

type DynamicPartitionAccessObjects []*DynamicPartitionAccessObject

DynamicPartitionAccessObjects is a list of DynamicPartitionAccessObject.

func (DynamicPartitionAccessObjects) NormalizedString

func (d DynamicPartitionAccessObjects) NormalizedString() string

NormalizedString implements AccessObject.

func (DynamicPartitionAccessObjects) SetIntoPB

func (d DynamicPartitionAccessObjects) SetIntoPB(pb *tipb.ExplainOperator)

SetIntoPB implements AccessObject.

func (DynamicPartitionAccessObjects) String

type ErrExprLoc

type ErrExprLoc struct {
	Offset int
	Loc    string
}

ErrExprLoc is for generate the ErrFieldNotInGroupBy error info

type Execute

type Execute struct {
	Name     string
	Params   []expression.Expression
	PrepStmt *PlanCacheStmt
	Stmt     ast.StmtNode
	Plan     base.Plan
	// contains filtered or unexported fields
}

Execute represents prepare plan.

func (*Execute) MemoryUsage

func (s *Execute) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*Execute) OutputNames

func (s *Execute) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Execute) ResolveIndices

func (*Execute) ResolveIndices() (err error)

func (*Execute) Schema

func (s *Execute) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Execute) SetOutputNames

func (s *Execute) SetOutputNames(names types.NameSlice)

func (*Execute) SetSchema

func (s *Execute) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type Explain

type Explain struct {
	TargetPlan       base.Plan
	Format           string
	Analyze          bool
	ExecStmt         ast.StmtNode
	RuntimeStatsColl *execdetails.RuntimeStatsColl

	Rows        [][]string
	ExplainRows [][]string
	// contains filtered or unexported fields
}

Explain represents a explain plan.

func (*Explain) MemoryUsage

func (s *Explain) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*Explain) OutputNames

func (s *Explain) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Explain) RenderResult

func (e *Explain) RenderResult() error

RenderResult renders the explain result as specified format.

func (*Explain) ResolveIndices

func (*Explain) ResolveIndices() (err error)

func (*Explain) Schema

func (s *Explain) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Explain) SetOutputNames

func (s *Explain) SetOutputNames(names types.NameSlice)

func (*Explain) SetSchema

func (s *Explain) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ExplainInfoForEncode

type ExplainInfoForEncode struct {
	ID                  string                  `json:"id"`
	EstRows             string                  `json:"estRows"`
	ActRows             string                  `json:"actRows,omitempty"`
	TaskType            string                  `json:"taskType"`
	AccessObject        string                  `json:"accessObject,omitempty"`
	ExecuteInfo         string                  `json:"executeInfo,omitempty"`
	OperatorInfo        string                  `json:"operatorInfo,omitempty"`
	EstCost             string                  `json:"estCost,omitempty"`
	CostFormula         string                  `json:"costFormula,omitempty"`
	MemoryInfo          string                  `json:"memoryInfo,omitempty"`
	DiskInfo            string                  `json:"diskInfo,omitempty"`
	TotalMemoryConsumed string                  `json:"totalMemoryConsumed,omitempty"`
	SubOperators        []*ExplainInfoForEncode `json:"subOperators,omitempty"`
}

ExplainInfoForEncode store explain info for JSON encode

type ExprColumnMap

type ExprColumnMap map[expression.Expression]*expression.Column

ExprColumnMap is used to store all expressions of indexed generated columns in a table, and map them to the generated columns, thus we can substitute the expression in a query to an indexed generated column.

type FKCascade

type FKCascade struct {
	physicalop.BasePhysicalPlan
	Tp         FKCascadeType
	ReferredFK *model.ReferredFKInfo
	ChildTable table.Table
	FK         *model.FKInfo
	FKCols     []*model.ColumnInfo
	FKIdx      *model.IndexInfo
	// CascadePlans contains the child cascade plan.
	// CascadePlans will be filled during execution, so only `explain analyze` statement result contains the cascade plan,
	// `explain` statement result doesn't contain the cascade plan.
	CascadePlans []base.Plan
}

FKCascade indicates the foreign key constraint cascade behaviour.

func (*FKCascade) AccessObject

func (f *FKCascade) AccessObject() base.AccessObject

AccessObject implements dataAccesser interface.

func (*FKCascade) ExplainInfo

func (f *FKCascade) ExplainInfo() string

ExplainInfo implement Plan interface.

func (FKCascade) Init

func (p FKCascade) Init(ctx base.PlanContext) *FKCascade

Init initializes FKCascade

func (*FKCascade) MemoryUsage

func (f *FKCascade) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of FKCascade

func (*FKCascade) OperatorInfo

func (f *FKCascade) OperatorInfo(bool) string

OperatorInfo implements dataAccesser interface.

type FKCascadeType

type FKCascadeType int8

FKCascadeType indicates in which (delete/update) statements.

const (
	// FKCascadeOnDelete indicates in delete statement.
	FKCascadeOnDelete FKCascadeType = 1
	// FKCascadeOnUpdate indicates in update statement.
	FKCascadeOnUpdate FKCascadeType = 2
)

type FKCheck

type FKCheck struct {
	physicalop.BasePhysicalPlan
	FK         *model.FKInfo
	ReferredFK *model.ReferredFKInfo
	Tbl        table.Table
	Idx        table.Index
	Cols       []pmodel.CIStr

	IdxIsPrimaryKey bool
	IdxIsExclusive  bool

	CheckExist bool
	FailedErr  error
}

FKCheck indicates the foreign key constraint checker.

func (*FKCheck) AccessObject

func (f *FKCheck) AccessObject() base.AccessObject

AccessObject implements dataAccesser interface.

func (*FKCheck) ExplainInfo

func (f *FKCheck) ExplainInfo() string

ExplainInfo implement Plan interface.

func (FKCheck) Init

func (p FKCheck) Init(ctx base.PlanContext) *FKCheck

Init initializes FKCheck.

func (*FKCheck) MemoryUsage

func (f *FKCheck) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of FKCheck

func (*FKCheck) OperatorInfo

func (f *FKCheck) OperatorInfo(bool) string

OperatorInfo implements dataAccesser interface.

type FlatOperator

type FlatOperator struct {
	// A reference to the original operator.
	Origin base.Plan

	// ChildrenIdx is the indexes of the children of this operator in the FlatPlanTree.
	// It's ordered from small to large.
	ChildrenIdx []int
	// ChildrenEndIdx is the index of the last operator of children subtrees of this operator in the FlatPlanTree.
	ChildrenEndIdx int

	// NeedReverseDriverSide means if we need to reverse the order of children to keep build side before probe side.
	//
	// Specifically, it means if the below are all true:
	// 1. this operator has two children
	// 2. the first child's Label is the probe side and the second's is the build side.
	//
	// If you call FlattenPhysicalPlan with buildSideFirst true, NeedReverseDriverSide will be useless.
	NeedReverseDriverSide bool

	Depth     uint32
	Label     OperatorLabel
	IsRoot    bool
	StoreType kv.StoreType
	// ReqType is only meaningful when IsRoot is false.
	ReqType ReadReqType

	// The below two fields are mainly for text tree formatting. See texttree.PrettyIdentifier().
	TextTreeIndent string
	IsLastChild    bool

	IsPhysicalPlan bool
}

FlatOperator is a simplified operator. It contains a reference to the original operator and some usually needed information.

type FlatPhysicalPlan

type FlatPhysicalPlan struct {
	Main             FlatPlanTree
	CTEs             []FlatPlanTree
	ScalarSubQueries []FlatPlanTree

	// InExecute means if the original plan tree contains Execute operator.
	//
	// Be careful when trying to use this, InExecute is true doesn't mean we are handling an EXECUTE statement.
	// When collecting information from the plan in an EXECUTE statement, usually we directly use the plan
	// in Execute.Plan, not Execute itself, so InExecute will be false.
	//
	// When will InExecute be true? When you're using "EXPLAIN FOR CONNECTION" to get the last plan of
	// a connection (usually we will record Explain.TargetPlan for an EXPLAIN statement) and that plan
	// is from an EXECUTE statement, we will collect from Execute itself, not directly from Execute.Plan,
	// then InExecute will be true.
	InExecute bool

	// InExplain means if the original plan tree contains Explain operator.
	InExplain bool
	// contains filtered or unexported fields
}

FlatPhysicalPlan provides an easier structure to traverse a plan and collect needed information. Note: Although it's named FlatPhysicalPlan, there also could be Insert, Delete and Update at the beginning of Main.

func FlattenPhysicalPlan

func FlattenPhysicalPlan(p base.Plan, buildSideFirst bool) *FlatPhysicalPlan

FlattenPhysicalPlan generates a FlatPhysicalPlan from a PhysicalPlan, Insert, Delete, Update, Explain or Execute.

type FlatPlanTree

type FlatPlanTree []*FlatOperator

FlatPlanTree is a simplified plan tree. It arranges all operators in the tree as a slice, ordered by the order of traversing the tree, which means a depth-first traversal plus some special rule for some operators.

func (FlatPlanTree) GetSelectPlan

func (e FlatPlanTree) GetSelectPlan() (FlatPlanTree, int)

GetSelectPlan skips Insert, Delete, and Update at the beginning of the FlatPlanTree and the foreign key check/cascade plan at the end of the FlatPlanTree. Note:

It returns a reference to the original FlatPlanTree, please avoid modifying the returned value.
The second return value is the offset. Because the returned FlatPlanTree is a part of the original slice, you need to minus them by the offset when using the returned FlatOperator.Depth and FlatOperator.ChildrenIdx.

type Fragment

type Fragment struct {
	// following field are filled during getPlanFragment.
	TableScan         *PhysicalTableScan          // result physical table scan
	ExchangeReceivers []*PhysicalExchangeReceiver // data receivers
	CTEReaders        []*PhysicalCTE              // The receivers for CTE storage/producer.

	// following fields are filled after scheduling.
	ExchangeSender *PhysicalExchangeSender // data exporter

	IsRoot bool
	// contains filtered or unexported fields
}

Fragment is cut from the whole pushed-down plan by network communication. Communication by pfs are always through shuffling / broadcasting / passing through.

func GenerateRootMPPTasks

func GenerateRootMPPTasks(ctx sessionctx.Context, startTs uint64, mppGatherID uint64,
	mppQueryID kv.MPPQueryID, sender *PhysicalExchangeSender, is infoschema.InfoSchema) ([]*Fragment, []kv.KeyRange, map[string]bool, error)

GenerateRootMPPTasks generate all mpp tasks and return root ones.

func (*Fragment) MemoryUsage

func (f *Fragment) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of Fragment

type GcSubstituter

type GcSubstituter struct {
}

GcSubstituter is used to substitute the expression to indexed virtual generated column in where, group by, order by, and field clause.

func (*GcSubstituter) Name

func (*GcSubstituter) Name() string

Name implements base.LogicalOptRule.<1st> interface.

func (*GcSubstituter) Optimize

Optimize implements base.LogicalOptRule.<0th> interface. optimize try to replace the expression to indexed virtual generate column in where, group by, order by, and field clause so that we can use the index on expression. For example: select a+1 from t order by a+1, with a virtual generate column c as (a+1) and an index on c. We need to replace a+1 with c so that we can use the index on c. See also https://dev.mysql.com/doc/refman/8.0/en/generated-column-index-optimizations.html

type HashJoinCPUCostDetail

type HashJoinCPUCostDetail struct {
	BuildRowCount       float64                  `json:"buildRowCount"`
	CPUFactor           float64                  `json:"cpuFactor"`
	ConcurrencyFactor   float64                  `json:"concurrencyFactor"`
	ProbeCost           *HashJoinProbeCostDetail `json:"probeCost"`
	HashJoinConcurrency uint                     `json:"hashJoinConcurrency"`
	Spill               bool                     `json:"spill"`
	Cost                float64                  `json:"cost"`
	UseOuterToBuild     bool                     `json:"useOuterToBuild"`
}

HashJoinCPUCostDetail indicates cpu cost detail

type HashJoinDiskCostDetail

type HashJoinDiskCostDetail struct {
	Spill           bool                         `json:"spill"`
	UseOuterToBuild bool                         `json:"useOuterToBuild"`
	BuildRowCount   float64                      `json:"buildRowCount"`
	DiskFactor      float64                      `json:"diskFactor"`
	RowSize         float64                      `json:"rowSize"`
	ProbeDiskCost   *HashJoinProbeDiskCostDetail `json:"probeDiskCost"`
	Cost            float64                      `json:"cost"`
}

HashJoinDiskCostDetail indicates disk cost detail

type HashJoinMemoryCostDetail

type HashJoinMemoryCostDetail struct {
	Spill         bool    `json:"spill"`
	MemQuota      int64   `json:"memQuota"`
	RowSize       float64 `json:"rowSize"`
	BuildRowCount float64 `json:"buildRowCount"`
	MemoryFactor  float64 `json:"memoryFactor"`
	Cost          float64 `json:"cost"`
}

HashJoinMemoryCostDetail indicates memory cost detail

type HashJoinProbeCostDetail

type HashJoinProbeCostDetail struct {
	NumPairs        float64 `json:"numPairs"`
	HasConditions   bool    `json:"hasConditions"`
	SelectionFactor float64 `json:"selectionFactor"`
	ProbeRowCount   float64 `json:"probeRowCount"`
	Cost            float64 `json:"cost"`
}

HashJoinProbeCostDetail indicates probe cpu cost detail

type HashJoinProbeDiskCostDetail

type HashJoinProbeDiskCostDetail struct {
	SelectionFactor float64 `json:"selectionFactor"`
	NumPairs        float64 `json:"numPairs"`
	HasConditions   bool    `json:"hasConditions"`
	Cost            float64 `json:"cost"`
}

HashJoinProbeDiskCostDetail indicates probe disk cost detail

type HotRegionsHistoryTableExtractor

type HotRegionsHistoryTableExtractor struct {

	// SkipRequest means the where clause always false, we don't need to request any pd server.
	SkipRequest bool

	// StartTime represents the beginning time of update time.
	// e.g: SELECT * FROM tidb_hot_regions_history WHERE update_time>'2019-10-10 10:10:10.999'
	StartTime int64
	// EndTime represents the ending time of update time.
	// e.g: SELECT * FROM tidb_hot_regions_history WHERE update_time<'2019-10-11 10:10:10.999'
	EndTime int64

	// RegionIDs/StoreIDs/PeerIDs represents all region/store/peer ids we should filter in PD to reduce network IO.
	// e.g:
	// 1. SELECT * FROM tidb_hot_regions_history WHERE region_id=1
	// 2. SELECT * FROM tidb_hot_regions_history WHERE table_id in (11, 22)
	// Leave range operation to above selection executor.
	RegionIDs []uint64
	StoreIDs  []uint64
	PeerIDs   []uint64
	// IsLearners/IsLeaders represents whether we should request for learner/leader role in PD to reduce network IO.
	// e.g:
	// 1. SELECT * FROM tidb_hot_regions_history WHERE is_learner=1
	// 2. SELECT * FROM tidb_hot_regions_history WHERE is_learner in (0,1) -> request all
	IsLearners []bool
	IsLeaders  []bool

	// HotRegionTypes represents all hot region types we should filter in PD to reduce network IO.
	// e.g:
	// 1. SELECT * FROM tidb_hot_regions_history WHERE type='read'
	// 2. SELECT * FROM tidb_hot_regions_history WHERE type in ('read', 'write')
	// 3. SELECT * FROM tidb_hot_regions_history WHERE type='read' and type='write' -> SkipRequest = true
	HotRegionTypes set.StringSet
	// contains filtered or unexported fields
}

HotRegionsHistoryTableExtractor is used to extract some predicates of `tidb_hot_regions_history`

func (*HotRegionsHistoryTableExtractor) ExplainInfo

ExplainInfo implements the base.MemTablePredicateExtractor interface.

func (*HotRegionsHistoryTableExtractor) Extract

Extract implements the MemTablePredicateExtractor Extract interface

type ImportInto

type ImportInto struct {
	Table              *resolve.TableNameW
	ColumnAssignments  []*ast.Assignment
	ColumnsAndUserVars []*ast.ColumnNameOrUserVar
	Path               string
	Format             *string
	Options            []*LoadDataOpt

	GenCols InsertGeneratedColumns
	Stmt    string

	SelectPlan base.PhysicalPlan
	// contains filtered or unexported fields
}

ImportInto represents a ingest into plan.

func (ImportInto) Init

func (p ImportInto) Init(ctx base.PlanContext) *ImportInto

Init initializes ImportInto.

func (*ImportInto) MemoryUsage

func (s *ImportInto) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*ImportInto) OutputNames

func (s *ImportInto) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*ImportInto) ResolveIndices

func (*ImportInto) ResolveIndices() (err error)

func (*ImportInto) Schema

func (s *ImportInto) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*ImportInto) SetOutputNames

func (s *ImportInto) SetOutputNames(names types.NameSlice)

func (*ImportInto) SetSchema

func (s *ImportInto) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type IndexAccess

type IndexAccess struct {
	Name             string
	Cols             []string
	IsClusteredIndex bool
}

IndexAccess represents the index accessed by an operator.

func (*IndexAccess) ToPB

func (a *IndexAccess) ToPB() *tipb.IndexAccess

ToPB turns itself into a protobuf message.

type IndexUsageIndexInfo

type IndexUsageIndexInfo struct {
	Name string
	ID   int64
}

IndexUsageIndexInfo is the necessary index info for information_schema.tidb_index_usage. It only includes the index name and ID in lower case.

type InfoSchemaBaseExtractor

type InfoSchemaBaseExtractor struct {

	// SkipRequest means the where clause always false, we don't need to request any component
	SkipRequest bool
	// ColPredicates records the columns that can be extracted from the predicates.
	// For example, `select * from information_schema.SCHEMATA where schema_name='mysql' or schema_name='INFORMATION_SCHEMA'`
	// {"schema_name": ["mysql", "INFORMATION_SCHEMA"]}
	ColPredicates map[string]set.StringSet

	// used for EXPLAIN only
	LikePatterns map[string][]string
	// contains filtered or unexported fields
}

InfoSchemaBaseExtractor is used to extract infoSchema tables related predicates.

func (*InfoSchemaBaseExtractor) ExplainInfo

func (e *InfoSchemaBaseExtractor) ExplainInfo(_ base.PhysicalPlan) string

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*InfoSchemaBaseExtractor) Extract

func (e *InfoSchemaBaseExtractor) Extract(
	ctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) (remained []expression.Expression)

Extract implements the MemTablePredicateExtractor Extract interface

func (*InfoSchemaBaseExtractor) GetBase

GetBase is only used for test.

func (*InfoSchemaBaseExtractor) ListSchemas

ListSchemas lists all schemas from predicate. If no schema is specified, it lists all schemas in the storage.

func (*InfoSchemaBaseExtractor) ListSchemasAndTables

func (e *InfoSchemaBaseExtractor) ListSchemasAndTables(
	ctx context.Context,
	is infoschema.InfoSchema,
) ([]pmodel.CIStr, []*model.TableInfo, error)

ListSchemasAndTables lists related tables and their corresponding schemas from predicate. If there is no error, returning schema slice and table slice are guaranteed to have the same length.

type InfoSchemaCheckConstraintsExtractor

type InfoSchemaCheckConstraintsExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaCheckConstraintsExtractor is the predicate extractor for information_schema.check_constraints.

func NewInfoSchemaCheckConstraintsExtractor

func NewInfoSchemaCheckConstraintsExtractor() *InfoSchemaCheckConstraintsExtractor

NewInfoSchemaCheckConstraintsExtractor creates a new InfoSchemaCheckConstraintsExtractor.

func (*InfoSchemaCheckConstraintsExtractor) HasConstraint

func (e *InfoSchemaCheckConstraintsExtractor) HasConstraint(name string) bool

HasConstraint returns true if constraint name is specified in predicates.

type InfoSchemaColumnsExtractor

type InfoSchemaColumnsExtractor struct {
	InfoSchemaBaseExtractor
	// contains filtered or unexported fields
}

InfoSchemaColumnsExtractor is the predicate extractor for information_schema.columns.

func NewInfoSchemaColumnsExtractor

func NewInfoSchemaColumnsExtractor() *InfoSchemaColumnsExtractor

NewInfoSchemaColumnsExtractor creates a new InfoSchemaColumnsExtractor.

func (*InfoSchemaColumnsExtractor) ListColumns

func (e *InfoSchemaColumnsExtractor) ListColumns(
	tbl *model.TableInfo,
) ([]*model.ColumnInfo, []int)

ListColumns lists unhidden columns and corresponding ordinal positions for given table from predicates. If no column found in predicate, it return all visible columns.

func (*InfoSchemaColumnsExtractor) ListTables

ListTables lists related tables for given schema from predicate. If no table found in predicate, it return all tables. TODO(tangenta): remove this after streaming interface is supported.

type InfoSchemaDDLExtractor

type InfoSchemaDDLExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaDDLExtractor is the predicate extractor for information_schema.ddl_jobs.

func NewInfoSchemaDDLExtractor

func NewInfoSchemaDDLExtractor() *InfoSchemaDDLExtractor

NewInfoSchemaDDLExtractor creates a new InfoSchemaDDLExtractor.

func (*InfoSchemaDDLExtractor) Extract

func (e *InfoSchemaDDLExtractor) Extract(
	ctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) (remained []expression.Expression)

Extract implements the MemTablePredicateExtractor Extract interface

Different from other extractor, input predicates will not be pruned. For example, we will use state to determine whether to scan history ddl jobs, but we don't not use these predicates to do filtering. So the Selection Operator is still needed.

type InfoSchemaIndexesExtractor

type InfoSchemaIndexesExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaIndexesExtractor is the predicate extractor for information_schema.tidb_indexes.

func NewInfoSchemaIndexesExtractor

func NewInfoSchemaIndexesExtractor() *InfoSchemaIndexesExtractor

NewInfoSchemaIndexesExtractor creates a new InfoSchemaIndexesExtractor.

type InfoSchemaKeyColumnUsageExtractor

type InfoSchemaKeyColumnUsageExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaKeyColumnUsageExtractor is the predicate extractor for information_schema.key_column_usage.

func NewInfoSchemaKeyColumnUsageExtractor

func NewInfoSchemaKeyColumnUsageExtractor() *InfoSchemaKeyColumnUsageExtractor

NewInfoSchemaKeyColumnUsageExtractor creates a new InfoSchemaKeyColumnUsageExtractor.

func (*InfoSchemaKeyColumnUsageExtractor) HasConstraint

func (e *InfoSchemaKeyColumnUsageExtractor) HasConstraint(name string) bool

HasConstraint returns true if constraint name is specified in predicates.

func (*InfoSchemaKeyColumnUsageExtractor) HasConstraintSchema

func (e *InfoSchemaKeyColumnUsageExtractor) HasConstraintSchema(name string) bool

HasConstraintSchema returns true if constraint schema is specified in predicates.

func (*InfoSchemaKeyColumnUsageExtractor) HasPrimaryKey

func (e *InfoSchemaKeyColumnUsageExtractor) HasPrimaryKey() bool

HasPrimaryKey returns true if primary key is specified in predicates.

type InfoSchemaPartitionsExtractor

type InfoSchemaPartitionsExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaPartitionsExtractor is the predicate extractor for information_schema.partitions.

func NewInfoSchemaPartitionsExtractor

func NewInfoSchemaPartitionsExtractor() *InfoSchemaPartitionsExtractor

NewInfoSchemaPartitionsExtractor creates a new InfoSchemaPartitionsExtractor.

func (*InfoSchemaPartitionsExtractor) HasPartition

func (e *InfoSchemaPartitionsExtractor) HasPartition(name string) bool

HasPartition returns true if partition name matches the one in predicates.

func (*InfoSchemaPartitionsExtractor) HasPartitionPred

func (e *InfoSchemaPartitionsExtractor) HasPartitionPred() bool

HasPartitionPred returns true if partition name is specified in predicates.

type InfoSchemaReferConstExtractor

type InfoSchemaReferConstExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaReferConstExtractor is the predicate extractor for information_schema.referential_constraints.

func NewInfoSchemaReferConstExtractor

func NewInfoSchemaReferConstExtractor() *InfoSchemaReferConstExtractor

NewInfoSchemaReferConstExtractor creates a new InfoSchemaReferConstExtractor.

func (*InfoSchemaReferConstExtractor) HasConstraint

func (e *InfoSchemaReferConstExtractor) HasConstraint(name string) bool

HasConstraint returns true if constraint name is specified in predicates.

type InfoSchemaSchemataExtractor

type InfoSchemaSchemataExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaSchemataExtractor is the predicate extractor for information_schema.schemata.

func NewInfoSchemaSchemataExtractor

func NewInfoSchemaSchemataExtractor() *InfoSchemaSchemataExtractor

NewInfoSchemaSchemataExtractor creates a new InfoSchemaSchemataExtractor.

type InfoSchemaSequenceExtractor

type InfoSchemaSequenceExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaSequenceExtractor is the predicate extractor for information_schema.sequences.

func NewInfoSchemaSequenceExtractor

func NewInfoSchemaSequenceExtractor() *InfoSchemaSequenceExtractor

NewInfoSchemaSequenceExtractor creates a new InfoSchemaSequenceExtractor.

type InfoSchemaStatisticsExtractor

type InfoSchemaStatisticsExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaStatisticsExtractor is the predicate extractor for information_schema.statistics.

func NewInfoSchemaStatisticsExtractor

func NewInfoSchemaStatisticsExtractor() *InfoSchemaStatisticsExtractor

NewInfoSchemaStatisticsExtractor creates a new InfoSchemaStatisticsExtractor.

func (*InfoSchemaStatisticsExtractor) HasIndex

func (e *InfoSchemaStatisticsExtractor) HasIndex(val string) bool

HasIndex returns true if index name is specified in predicates.

func (*InfoSchemaStatisticsExtractor) HasPrimaryKey

func (e *InfoSchemaStatisticsExtractor) HasPrimaryKey() bool

HasPrimaryKey returns true if primary key is specified in predicates.

type InfoSchemaTableConstraintsExtractor

type InfoSchemaTableConstraintsExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaTableConstraintsExtractor is the predicate extractor for information_schema.constraints.

func NewInfoSchemaTableConstraintsExtractor

func NewInfoSchemaTableConstraintsExtractor() *InfoSchemaTableConstraintsExtractor

NewInfoSchemaTableConstraintsExtractor creates a new InfoSchemaTableConstraintsExtractor.

func (*InfoSchemaTableConstraintsExtractor) HasConstraint

func (e *InfoSchemaTableConstraintsExtractor) HasConstraint(name string) bool

HasConstraint returns true if constraint is specified in predicates.

func (*InfoSchemaTableConstraintsExtractor) HasConstraintSchema

func (e *InfoSchemaTableConstraintsExtractor) HasConstraintSchema(name string) bool

HasConstraintSchema returns true if constraint schema is specified in predicates.

func (*InfoSchemaTableConstraintsExtractor) HasPrimaryKey

func (e *InfoSchemaTableConstraintsExtractor) HasPrimaryKey() bool

HasPrimaryKey returns true if primary key is specified in predicates.

type InfoSchemaTablesExtractor

type InfoSchemaTablesExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaTablesExtractor is the predicate extractor for information_schema.tables.

func NewInfoSchemaTablesExtractor

func NewInfoSchemaTablesExtractor() *InfoSchemaTablesExtractor

NewInfoSchemaTablesExtractor creates a new InfoSchemaTablesExtractor.

func (*InfoSchemaTablesExtractor) HasTableName

func (e *InfoSchemaTablesExtractor) HasTableName(name string) bool

HasTableName returns true if table name is specified in predicates.

func (*InfoSchemaTablesExtractor) HasTableSchema

func (e *InfoSchemaTablesExtractor) HasTableSchema(name string) bool

HasTableSchema returns true if table schema is specified in predicates.

type InfoSchemaTiDBCheckConstraintsExtractor

type InfoSchemaTiDBCheckConstraintsExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaTiDBCheckConstraintsExtractor is the predicate extractor for information_schema.tidb_check_constraints.

func NewInfoSchemaTiDBCheckConstraintsExtractor

func NewInfoSchemaTiDBCheckConstraintsExtractor() *InfoSchemaTiDBCheckConstraintsExtractor

NewInfoSchemaTiDBCheckConstraintsExtractor creates a new InfoSchemaTiDBCheckConstraintsExtractor.

func (*InfoSchemaTiDBCheckConstraintsExtractor) HasConstraint

func (e *InfoSchemaTiDBCheckConstraintsExtractor) HasConstraint(name string) bool

HasConstraint returns true if constraint name is specified in predicates.

type InfoSchemaTiDBIndexUsageExtractor

type InfoSchemaTiDBIndexUsageExtractor struct {
	InfoSchemaBaseExtractor
	// contains filtered or unexported fields
}

InfoSchemaTiDBIndexUsageExtractor is the predicate extractor for information_schema.tidb_index_usage.

func NewInfoSchemaTiDBIndexUsageExtractor

func NewInfoSchemaTiDBIndexUsageExtractor() *InfoSchemaTiDBIndexUsageExtractor

NewInfoSchemaTiDBIndexUsageExtractor creates a new InfoSchemaTiDBIndexUsageExtractor.

func (*InfoSchemaTiDBIndexUsageExtractor) ListIndexes

ListIndexes lists related indexes for given table from predicate. If no index found in predicate, it return all indexes.

type InfoSchemaViewsExtractor

type InfoSchemaViewsExtractor struct {
	InfoSchemaBaseExtractor
}

InfoSchemaViewsExtractor is the predicate extractor for information_schema.views.

func NewInfoSchemaViewsExtractor

func NewInfoSchemaViewsExtractor() *InfoSchemaViewsExtractor

NewInfoSchemaViewsExtractor creates a new InfoSchemaViewsExtractor.

type Insert

type Insert struct {
	Table table.Table `plan-cache-clone:"shallow"`

	Columns []*ast.ColumnName `plan-cache-clone:"shallow"`
	Lists   [][]expression.Expression

	OnDuplicate        []*expression.Assignment
	Schema4OnDuplicate *expression.Schema `plan-cache-clone:"shallow"`

	GenCols InsertGeneratedColumns

	SelectPlan base.PhysicalPlan

	IsReplace bool
	IgnoreErr bool

	// NeedFillDefaultValue is true when expr in value list reference other column.
	NeedFillDefaultValue bool

	AllAssignmentsAreConstant bool

	RowLen int

	FKChecks   []*FKCheck   `plan-cache-clone:"must-nil"`
	FKCascades []*FKCascade `plan-cache-clone:"must-nil"`
	// contains filtered or unexported fields
}

Insert represents an insert plan.

func (*Insert) CloneForPlanCache

func (op *Insert) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (Insert) Init

func (p Insert) Init(ctx base.PlanContext) *Insert

Init initializes Insert.

func (*Insert) MemoryUsage

func (p *Insert) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of Insert

func (*Insert) OutputNames

func (s *Insert) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Insert) ResolveIndices

func (p *Insert) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*Insert) Schema

func (s *Insert) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Insert) SetOutputNames

func (s *Insert) SetOutputNames(names types.NameSlice)

func (*Insert) SetSchema

func (s *Insert) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type InsertGeneratedColumns

type InsertGeneratedColumns struct {
	Exprs        []expression.Expression
	OnDuplicates []*expression.Assignment
}

InsertGeneratedColumns is for completing generated columns in Insert. We resolve generation expressions in plan, and eval those in executor.

func (*InsertGeneratedColumns) MemoryUsage

func (i *InsertGeneratedColumns) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of InsertGeneratedColumns

type InspectionResultTableExtractor

type InspectionResultTableExtractor struct {

	// SkipInspection means the where clause always false, we don't need to request any component
	SkipInspection bool
	// Rules represents rules applied to, and we should apply all inspection rules if there is no rules specified
	// e.g: SELECT * FROM inspection_result WHERE rule in ('ddl', 'config')
	Rules set.StringSet
	// Items represents items applied to, and we should apply all inspection item if there is no rules specified
	// e.g: SELECT * FROM inspection_result WHERE item in ('ddl.lease', 'raftstore.threadpool')
	Items set.StringSet
	// contains filtered or unexported fields
}

InspectionResultTableExtractor is used to extract some predicates of `inspection_result`

func (*InspectionResultTableExtractor) ExplainInfo

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*InspectionResultTableExtractor) Extract

func (e *InspectionResultTableExtractor) Extract(ctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) (remained []expression.Expression)

Extract implements the MemTablePredicateExtractor Extract interface

type InspectionRuleTableExtractor

type InspectionRuleTableExtractor struct {
	SkipRequest bool
	Types       set.StringSet
	// contains filtered or unexported fields
}

InspectionRuleTableExtractor is used to extract some predicates of `inspection_rules`

func (*InspectionRuleTableExtractor) ExplainInfo

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*InspectionRuleTableExtractor) Extract

func (e *InspectionRuleTableExtractor) Extract(ctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) (remained []expression.Expression)

Extract implements the MemTablePredicateExtractor Extract interface

type InspectionSummaryTableExtractor

type InspectionSummaryTableExtractor struct {

	// SkipInspection means the where clause always false, we don't need to request any component
	SkipInspection bool
	// Rules represents rules applied to, and we should apply all inspection rules if there is no rules specified
	// e.g: SELECT * FROM inspection_summary WHERE rule in ('ddl', 'config')
	Rules       set.StringSet
	MetricNames set.StringSet
	Quantiles   []float64
	// contains filtered or unexported fields
}

InspectionSummaryTableExtractor is used to extract some predicates of `inspection_summary`

func (*InspectionSummaryTableExtractor) ExplainInfo

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*InspectionSummaryTableExtractor) Extract

func (e *InspectionSummaryTableExtractor) Extract(ctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) (remained []expression.Expression)

Extract implements the MemTablePredicateExtractor Extract interface

type JoinReOrderSolver

type JoinReOrderSolver struct {
}

JoinReOrderSolver is used to reorder the join nodes in a logical plan.

func (*JoinReOrderSolver) Name

func (*JoinReOrderSolver) Name() string

Name implements the base.LogicalOptRule.<1st> interface.

func (*JoinReOrderSolver) Optimize

Optimize implements the base.LogicalOptRule.<0th> interface.

type LRUPlanCache

type LRUPlanCache struct {
	// contains filtered or unexported fields
}

LRUPlanCache is a dedicated least recently used cache, Only used for plan cache.

func NewLRUPlanCache

func NewLRUPlanCache(capacity uint, guard float64, quota uint64, sctx sessionctx.Context, _ bool) *LRUPlanCache

NewLRUPlanCache creates a PCLRUCache object, whose capacity is "capacity". NOTE: "capacity" should be a positive value.

func (*LRUPlanCache) Close

func (l *LRUPlanCache) Close()

Close do some clean work for LRUPlanCache when close the session

func (*LRUPlanCache) Delete

func (l *LRUPlanCache) Delete(key string)

Delete deletes the multi-values from the LRU Cache.

func (*LRUPlanCache) DeleteAll

func (l *LRUPlanCache) DeleteAll()

DeleteAll deletes all elements from the LRU Cache.

func (*LRUPlanCache) Get

func (l *LRUPlanCache) Get(key string, paramTypes any) (value any, ok bool)

Get tries to find the corresponding value according to the given key.

func (*LRUPlanCache) MemoryUsage

func (l *LRUPlanCache) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of LRUPlanCache

func (*LRUPlanCache) Put

func (l *LRUPlanCache) Put(key string, value, paramTypes any)

Put puts the (key, value) pair into the LRU Cache.

func (*LRUPlanCache) SetCapacity

func (l *LRUPlanCache) SetCapacity(capacity uint) error

SetCapacity sets capacity of the cache.

func (*LRUPlanCache) Size

func (l *LRUPlanCache) Size() int

Size gets the current cache size.

type LineFieldsInfo

type LineFieldsInfo struct {
	FieldsTerminatedBy string
	FieldsEnclosedBy   string // length always <= 1, see parser.y
	FieldsEscapedBy    string // length always <= 1, see parser.y
	FieldsOptEnclosed  bool
	LinesStartingBy    string
	LinesTerminatedBy  string
}

LineFieldsInfo used in load-data/select-into/index-advise stmt.

func NewLineFieldsInfo

func NewLineFieldsInfo(fieldsInfo *ast.FieldsClause, linesInfo *ast.LinesClause) LineFieldsInfo

NewLineFieldsInfo new LineFieldsInfo from FIELDS/LINES info.

type LoadData

type LoadData struct {
	FileLocRef  ast.FileLocRefTp
	OnDuplicate ast.OnDuplicateKeyHandlingType
	Path        string
	Format      *string
	Table       *resolve.TableNameW
	Charset     *string
	Columns     []*ast.ColumnName
	FieldsInfo  *ast.FieldsClause
	LinesInfo   *ast.LinesClause
	IgnoreLines *uint64

	ColumnAssignments  []*ast.Assignment
	ColumnsAndUserVars []*ast.ColumnNameOrUserVar
	Options            []*LoadDataOpt

	GenCols InsertGeneratedColumns
	// contains filtered or unexported fields
}

LoadData represents a loaddata plan.

func (LoadData) Init

func (p LoadData) Init(ctx base.PlanContext) *LoadData

Init initializes LoadData.

func (*LoadData) MemoryUsage

func (s *LoadData) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*LoadData) OutputNames

func (s *LoadData) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*LoadData) ResolveIndices

func (*LoadData) ResolveIndices() (err error)

func (*LoadData) Schema

func (s *LoadData) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*LoadData) SetOutputNames

func (s *LoadData) SetOutputNames(names types.NameSlice)

func (*LoadData) SetSchema

func (s *LoadData) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type LoadDataOpt

type LoadDataOpt struct {
	// Name is the name of the option, converted to lower case during parse.
	Name  string
	Value expression.Expression
}

LoadDataOpt represents load data option.

type LoadStats

type LoadStats struct {
	Path string
	// contains filtered or unexported fields
}

LoadStats represents a load stats plan.

func (*LoadStats) MemoryUsage

func (s *LoadStats) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*LoadStats) OutputNames

func (s *LoadStats) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*LoadStats) ResolveIndices

func (*LoadStats) ResolveIndices() (err error)

func (*LoadStats) Schema

func (s *LoadStats) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*LoadStats) SetOutputNames

func (s *LoadStats) SetOutputNames(names types.NameSlice)

func (*LoadStats) SetSchema

func (s *LoadStats) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type LockStats

type LockStats struct {
	Tables []*ast.TableName
	// contains filtered or unexported fields
}

LockStats represents a lock stats for table

func (*LockStats) MemoryUsage

func (s *LockStats) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*LockStats) OutputNames

func (s *LockStats) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*LockStats) ResolveIndices

func (*LockStats) ResolveIndices() (err error)

func (*LockStats) Schema

func (s *LockStats) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*LockStats) SetOutputNames

func (s *LockStats) SetOutputNames(names types.NameSlice)

func (*LockStats) SetSchema

func (s *LockStats) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type MaxMinEliminator

type MaxMinEliminator struct {
}

MaxMinEliminator tries to eliminate max/min aggregate function. For SQL like `select max(id) from t;`, we could optimize it to `select max(id) from (select id from t order by id desc limit 1 where id is not null) t;`. For SQL like `select min(id) from t;`, we could optimize it to `select min(id) from (select id from t order by id limit 1 where id is not null) t;`. For SQL like `select max(id), min(id) from t;`, we could optimize it to the cartesianJoin result of the two queries above if `id` has an index.

func (*MaxMinEliminator) Name

func (*MaxMinEliminator) Name() string

Name implements base.LogicalOptRule.<1st> interface.

func (*MaxMinEliminator) Optimize

Optimize implements base.LogicalOptRule.<0th> interface.

type MetricSummaryTableExtractor

type MetricSummaryTableExtractor struct {

	// SkipRequest means the where clause always false, we don't need to request any component
	SkipRequest  bool
	MetricsNames set.StringSet
	Quantiles    []float64
	// contains filtered or unexported fields
}

MetricSummaryTableExtractor is used to extract some predicates of metrics_schema tables.

func (*MetricSummaryTableExtractor) ExplainInfo

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*MetricSummaryTableExtractor) Extract

func (e *MetricSummaryTableExtractor) Extract(ctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) (remained []expression.Expression)

Extract implements the MemTablePredicateExtractor Extract interface

type MetricTableExtractor

type MetricTableExtractor struct {

	// SkipRequest means the where clause always false, we don't need to request any component
	SkipRequest bool
	// StartTime represents the beginning time of metric data.
	StartTime time.Time
	// EndTime represents the ending time of metric data.
	EndTime time.Time
	// LabelConditions represents the label conditions of metric data.
	LabelConditions map[string]set.StringSet
	Quantiles       []float64
	// contains filtered or unexported fields
}

MetricTableExtractor is used to extract some predicates of metrics_schema tables.

func (*MetricTableExtractor) ExplainInfo

func (e *MetricTableExtractor) ExplainInfo(pp base.PhysicalPlan) string

ExplainInfo implements the base.MemTablePredicateExtractor interface.

func (*MetricTableExtractor) Extract

func (e *MetricTableExtractor) Extract(ctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) []expression.Expression

Extract implements the MemTablePredicateExtractor Extract interface

func (*MetricTableExtractor) GetMetricTablePromQL

func (e *MetricTableExtractor) GetMetricTablePromQL(sctx base.PlanContext, lowerTableName string) string

GetMetricTablePromQL uses to get the promQL of metric table.

type MppTask

type MppTask struct {
	// contains filtered or unexported fields
}

MppTask can not : 1. keep order 2. support double read 3. consider virtual columns. 4. TODO: partition prune after close

func (*MppTask) ConvertToRootTask

func (t *MppTask) ConvertToRootTask(ctx base.PlanContext) base.Task

ConvertToRootTask implements Task interface.

func (*MppTask) ConvertToRootTaskImpl

func (t *MppTask) ConvertToRootTaskImpl(ctx base.PlanContext) *RootTask

ConvertToRootTaskImpl implements Task interface.

func (*MppTask) Copy

func (t *MppTask) Copy() base.Task

Copy implements Task interface.

func (*MppTask) Count

func (t *MppTask) Count() float64

Count implements Task interface.

func (*MppTask) Invalid

func (t *MppTask) Invalid() bool

Invalid implements Task interface.

func (*MppTask) MemoryUsage

func (t *MppTask) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of mppTask

func (*MppTask) Plan

func (t *MppTask) Plan() base.PhysicalPlan

Plan implements Task interface.

type NominalSort

type NominalSort struct {
	physicalop.BasePhysicalPlan

	// These two fields are used to switch ScalarFunctions to Constants. For these
	// NominalSorts, we need to converted to Projections check if the ScalarFunctions
	// are out of bounds. (issue #11653)
	ByItems    []*util.ByItems
	OnlyColumn bool
}

NominalSort asks sort properties for its child. It is a fake operator that will not appear in final physical operator tree. It will be eliminated or converted to Projection.

func (*NominalSort) Attach2Task

func (p *NominalSort) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (NominalSort) Init

func (p NominalSort) Init(ctx base.PlanContext, stats *property.StatsInfo, offset int, props ...*property.PhysicalProperty) *NominalSort

Init initializes NominalSort.

func (*NominalSort) MemoryUsage

func (ns *NominalSort) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of NominalSort

func (*NominalSort) ResolveIndices

func (p *NominalSort) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

type OperatorLabel

type OperatorLabel uint8

OperatorLabel acts as some additional information to the name, usually it means its relationship with its parent. It's useful for index join, apply, index lookup, cte and so on.

const (
	// Empty means OperatorLabel is meaningless for this operator.
	Empty OperatorLabel = iota
	// BuildSide means this operator is at the build side of its parent
	BuildSide
	// ProbeSide means this operator is at the probe side of its parent
	ProbeSide
	// SeedPart means this operator is the seed part of its parent (a cte)
	SeedPart
	// RecursivePart means this operator is the recursive part of its parent (a cte)
	RecursivePart
)

func (OperatorLabel) String

func (d OperatorLabel) String() string

type OtherAccessObject

type OtherAccessObject string

OtherAccessObject represents other kinds of access.

func (OtherAccessObject) NormalizedString

func (o OtherAccessObject) NormalizedString() string

NormalizedString implements AccessObject.

func (OtherAccessObject) SetIntoPB

func (o OtherAccessObject) SetIntoPB(pb *tipb.ExplainOperator)

SetIntoPB implements AccessObject.

func (OtherAccessObject) String

func (o OtherAccessObject) String() string

type OuterJoinEliminator

type OuterJoinEliminator struct {
}

OuterJoinEliminator is used to eliminate outer join.

func (*OuterJoinEliminator) Name

func (*OuterJoinEliminator) Name() string

Name implements base.LogicalOptRule.<1st> interface.

func (*OuterJoinEliminator) Optimize

Optimize implements base.LogicalOptRule.<0th> interface.

type PBPlanBuilder

type PBPlanBuilder struct {
	// contains filtered or unexported fields
}

PBPlanBuilder uses to build physical plan from dag protocol buffers.

func NewPBPlanBuilder

func NewPBPlanBuilder(sctx base.PlanContext, is infoschema.InfoSchema, ranges []*coprocessor.KeyRange) *PBPlanBuilder

NewPBPlanBuilder creates a new pb plan builder.

func (*PBPlanBuilder) Build

func (b *PBPlanBuilder) Build(executors []*tipb.Executor) (p base.PhysicalPlan, err error)

Build builds physical plan from dag protocol buffers.

type PPDSolver

type PPDSolver struct{}

PPDSolver stands for Predicate Push Down.

func (*PPDSolver) Name

func (*PPDSolver) Name() string

Name implements base.LogicalOptRule.<1st> interface.

func (*PPDSolver) Optimize

Optimize implements base.LogicalOptRule.<0th> interface.

type PartitionProcessor

type PartitionProcessor struct{}

PartitionProcessor rewrites the ast for table partition. Used by static partition prune mode.

// create table t (id int) partition by range (id) // (partition p1 values less than (10), // partition p2 values less than (20), // partition p3 values less than (30)) // // select * from t is equal to // select * from (union all // select * from p1 where id < 10 // select * from p2 where id < 20 // select * from p3 where id < 30)

PartitionProcessor is here because it's easier to prune partition after predicate push down.

func (*PartitionProcessor) Name

func (*PartitionProcessor) Name() string

Name implements the LogicalOptRule.<1st> interface.

func (*PartitionProcessor) Optimize

Optimize implements the LogicalOptRule.<0th> interface.

type PartitionSplitterType

type PartitionSplitterType int

PartitionSplitterType is the type of `Shuffle` executor splitter, which splits data source into partitions.

type PauseDDLJobs

type PauseDDLJobs struct {
	JobIDs []int64
	// contains filtered or unexported fields
}

PauseDDLJobs indicates a plan to pause the Running DDL Jobs.

func (*PauseDDLJobs) MemoryUsage

func (s *PauseDDLJobs) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*PauseDDLJobs) OutputNames

func (s *PauseDDLJobs) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*PauseDDLJobs) ResolveIndices

func (*PauseDDLJobs) ResolveIndices() (err error)

func (*PauseDDLJobs) Schema

func (s *PauseDDLJobs) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PauseDDLJobs) SetOutputNames

func (s *PauseDDLJobs) SetOutputNames(names types.NameSlice)

func (*PauseDDLJobs) SetSchema

func (s *PauseDDLJobs) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysPlanPartInfo

type PhysPlanPartInfo struct {
	PruningConds   []expression.Expression
	PartitionNames []pmodel.CIStr
	Columns        []*expression.Column
	ColumnNames    types.NameSlice
}

PhysPlanPartInfo indicates partition helper info in physical plan.

func (*PhysPlanPartInfo) MemoryUsage

func (pi *PhysPlanPartInfo) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysPlanPartInfo

type PhysicalApply

type PhysicalApply struct {
	PhysicalHashJoin

	CanUseCache bool
	Concurrency int
	OuterSchema []*expression.CorrelatedColumn
}

PhysicalApply represents apply plan, only used for subquery.

func (*PhysicalApply) Attach2Task

func (p *PhysicalApply) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalApply) Clone

func (la *PhysicalApply) Clone(newCtx base.PlanContext) (base.PhysicalPlan, error)

Clone implements op.PhysicalPlan interface.

func (*PhysicalApply) ExtractCorrelatedCols

func (la *PhysicalApply) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalApply) GetCost

func (p *PhysicalApply) GetCost(lCount, rCount, lCost, rCost float64) float64

GetCost computes the cost of apply operator.

func (*PhysicalApply) GetJoinType

func (p *PhysicalApply) GetJoinType() logicalop.JoinType

func (*PhysicalApply) GetPlanCostVer1

func (p *PhysicalApply) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalApply) GetPlanCostVer2

func (p *PhysicalApply) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = build-child-cost + build-filter-cost + probe-cost + probe-filter-cost probe-cost = probe-child-cost * build-rows

func (PhysicalApply) Init

func (p PhysicalApply) Init(ctx base.PlanContext, stats *property.StatsInfo, offset int, props ...*property.PhysicalProperty) *PhysicalApply

Init initializes PhysicalApply.

func (*PhysicalApply) MemoryUsage

func (la *PhysicalApply) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalApply

func (*PhysicalApply) PhysicalJoinImplement

func (*PhysicalApply) PhysicalJoinImplement() bool

PhysicalJoinImplement has an extra bool return value compared with PhysicalJoin interface. This will override basePhysicalJoin.PhysicalJoinImplement() and make PhysicalApply not an implementation of base.PhysicalJoin interface.

func (*PhysicalApply) ResolveIndices

func (p *PhysicalApply) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

type PhysicalCTE

type PhysicalCTE struct {
	SeedPlan  base.PhysicalPlan
	RecurPlan base.PhysicalPlan
	CTE       *logicalop.CTEClass
	// contains filtered or unexported fields
}

PhysicalCTE is for CTE.

func (*PhysicalCTE) AccessObject

func (p *PhysicalCTE) AccessObject() base.AccessObject

AccessObject implements physicalScan interface.

func (*PhysicalCTE) Clone

func (p *PhysicalCTE) Clone(newCtx base.PlanContext) (base.PhysicalPlan, error)

Clone implements op.PhysicalPlan interface.

func (*PhysicalCTE) ExplainID

func (p *PhysicalCTE) ExplainID() fmt.Stringer

ExplainID overrides the ExplainID.

func (*PhysicalCTE) ExplainInfo

func (p *PhysicalCTE) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalCTE) ExtractCorrelatedCols

func (p *PhysicalCTE) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalCTE) GetPlanCostVer2

func (p *PhysicalCTE) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 implements PhysicalPlan interface.

func (PhysicalCTE) Init

Init only assigns type and context.

func (*PhysicalCTE) MemoryUsage

func (p *PhysicalCTE) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalCTE

func (*PhysicalCTE) OperatorInfo

func (p *PhysicalCTE) OperatorInfo(_ bool) string

OperatorInfo implements dataAccesser interface.

func (*PhysicalCTE) ResolveIndices

func (p *PhysicalCTE) ResolveIndices() (err error)

func (*PhysicalCTE) Schema

func (s *PhysicalCTE) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalCTE) SetSchema

func (s *PhysicalCTE) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalCTEStorage

type PhysicalCTEStorage PhysicalCTE

PhysicalCTEStorage is used for representing CTE storage, or CTE producer in other words.

func (*PhysicalCTEStorage) Attach2Task

func (p *PhysicalCTEStorage) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements the PhysicalPlan interface.

func (*PhysicalCTEStorage) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalCTEStorage) ExplainID

func (p *PhysicalCTEStorage) ExplainID() fmt.Stringer

ExplainID overrides the ExplainID.

func (*PhysicalCTEStorage) ExplainInfo

func (*PhysicalCTEStorage) ExplainInfo() string

ExplainInfo overrides the ExplainInfo

func (*PhysicalCTEStorage) MemoryUsage

func (p *PhysicalCTEStorage) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of CTEDefinition

type PhysicalCTETable

type PhysicalCTETable struct {
	IDForStorage int
	// contains filtered or unexported fields
}

PhysicalCTETable is for CTE table.

func (*PhysicalCTETable) ExplainInfo

func (p *PhysicalCTETable) ExplainInfo() string

ExplainInfo overrides the ExplainInfo

func (PhysicalCTETable) Init

Init only assigns type and context.

func (*PhysicalCTETable) MemoryUsage

func (p *PhysicalCTETable) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalCTETable

func (*PhysicalCTETable) ResolveIndices

func (p *PhysicalCTETable) ResolveIndices() (err error)

func (*PhysicalCTETable) Schema

func (s *PhysicalCTETable) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalCTETable) SetSchema

func (s *PhysicalCTETable) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalExchangeReceiver

type PhysicalExchangeReceiver struct {
	physicalop.BasePhysicalPlan

	Tasks []*kv.MPPTask

	IsCTEReader bool
	// contains filtered or unexported fields
}

PhysicalExchangeReceiver accepts connection and receives data passively.

func (*PhysicalExchangeReceiver) Clone

Clone implment op.PhysicalPlan interface.

func (*PhysicalExchangeReceiver) ExplainInfo

func (p *PhysicalExchangeReceiver) ExplainInfo() (res string)

ExplainInfo implements Plan interface.

func (*PhysicalExchangeReceiver) GetExchangeSender

func (p *PhysicalExchangeReceiver) GetExchangeSender() *PhysicalExchangeSender

GetExchangeSender return the connected sender of this receiver. We assume that its child must be a receiver.

func (*PhysicalExchangeReceiver) GetPlanCostVer1

func (p *PhysicalExchangeReceiver) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalExchangeReceiver) GetPlanCostVer2

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = child-cost + net-cost

func (PhysicalExchangeReceiver) Init

Init only assigns type and context.

func (*PhysicalExchangeReceiver) MemoryUsage

func (p *PhysicalExchangeReceiver) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalExchangeReceiver

func (*PhysicalExchangeReceiver) ToPB

func (e *PhysicalExchangeReceiver) ToPB(ctx *base.BuildPBContext, _ kv.StoreType) (*tipb.Executor, error)

ToPB generates the pb structure.

type PhysicalExchangeSender

type PhysicalExchangeSender struct {
	physicalop.BasePhysicalPlan

	TargetTasks          []*kv.MPPTask
	TargetCTEReaderTasks [][]*kv.MPPTask
	ExchangeType         tipb.ExchangeType
	HashCols             []*property.MPPPartitionColumn
	// Tasks is the mpp task for current PhysicalExchangeSender.
	Tasks           []*kv.MPPTask
	CompressionMode kv.ExchangeCompressionMode
}

PhysicalExchangeSender dispatches data to upstream tasks. That means push mode processing.

func (*PhysicalExchangeSender) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalExchangeSender) ExplainInfo

func (p *PhysicalExchangeSender) ExplainInfo() string

ExplainInfo implements Plan interface.

func (PhysicalExchangeSender) Init

Init only assigns type and context.

func (*PhysicalExchangeSender) MemoryUsage

func (p *PhysicalExchangeSender) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalExchangeSender

func (*PhysicalExchangeSender) ResolveIndices

func (p *PhysicalExchangeSender) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalExchangeSender) ResolveIndicesItself

func (p *PhysicalExchangeSender) ResolveIndicesItself() (err error)

ResolveIndicesItself resolve indices for PhysicalPlan itself

func (*PhysicalExchangeSender) ToPB

func (e *PhysicalExchangeSender) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB generates the pb structure.

type PhysicalExpand

type PhysicalExpand struct {

	// generated grouping ID column itself.
	GroupingIDCol *expression.Column

	// GroupingSets is used to define what kind of group layout should the underlying data follow.
	// For simple case: select count(distinct a), count(distinct b) from t; the grouping expressions are [a] and [b].
	GroupingSets expression.GroupingSets

	// The level projections is generated from grouping sets,make execution more clearly.
	LevelExprs [][]expression.Expression

	// The generated column names. Eg: "grouping_id" and so on.
	ExtraGroupingColNames []string
	// contains filtered or unexported fields
}

PhysicalExpand is used to expand underlying data sources to feed different grouping sets.

func (*PhysicalExpand) Attach2Task

func (p *PhysicalExpand) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements the PhysicalPlan interface.

func (*PhysicalExpand) Clone

func (p *PhysicalExpand) Clone(newCtx base.PlanContext) (base.PhysicalPlan, error)

Clone implements op.PhysicalPlan interface.

func (*PhysicalExpand) ExplainInfo

func (p *PhysicalExpand) ExplainInfo() string

ExplainInfo implements Plan interface.

func (PhysicalExpand) Init

Init only assigns type and context.

func (*PhysicalExpand) MemoryUsage

func (p *PhysicalExpand) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalExpand

func (*PhysicalExpand) ResolveIndices

func (p *PhysicalExpand) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalExpand) ResolveIndicesItself

func (p *PhysicalExpand) ResolveIndicesItself() (err error)

ResolveIndicesItself resolve indices for PhysicalPlan itself

func (*PhysicalExpand) Schema

func (s *PhysicalExpand) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalExpand) SetSchema

func (s *PhysicalExpand) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

func (*PhysicalExpand) ToPB

func (p *PhysicalExpand) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalHashAgg

type PhysicalHashAgg struct {
	// contains filtered or unexported fields
}

PhysicalHashAgg is hash operator of aggregate.

func NewPhysicalHashAgg

func NewPhysicalHashAgg(la *logicalop.LogicalAggregation, newStats *property.StatsInfo, prop *property.PhysicalProperty) *PhysicalHashAgg

NewPhysicalHashAgg creates a new PhysicalHashAgg from a LogicalAggregation.

func (*PhysicalHashAgg) Attach2Task

func (p *PhysicalHashAgg) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements the PhysicalPlan interface.

func (*PhysicalHashAgg) Clone

func (p *PhysicalHashAgg) Clone(newCtx base.PlanContext) (base.PhysicalPlan, error)

Clone implements op.PhysicalPlan interface.

func (*PhysicalHashAgg) CloneForPlanCache

func (op *PhysicalHashAgg) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalHashAgg) ExplainInfo

func (p *PhysicalHashAgg) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalHashAgg) ExplainNormalizedInfo

func (p *PhysicalHashAgg) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalHashAgg) ExtractCorrelatedCols

func (p *PhysicalHashAgg) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalHashAgg) GetCost

func (p *PhysicalHashAgg) GetCost(inputRows float64, isRoot, isMPP bool, costFlag uint64) float64

GetCost computes the cost of hash aggregation considering CPU/memory.

func (*PhysicalHashAgg) GetPlanCostVer1

func (p *PhysicalHashAgg) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalHashAgg) GetPlanCostVer2

func (p *PhysicalHashAgg) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = child-cost + (agg-cost + group-cost + hash-build-cost + hash-probe-cost) / concurrency

func (PhysicalHashAgg) Init

func (base PhysicalHashAgg) Init(ctx base.PlanContext, stats *property.StatsInfo, offset int) *basePhysicalAgg

Init initializes basePhysicalAgg.

func (*PhysicalHashAgg) IsFinalAgg

func (p *PhysicalHashAgg) IsFinalAgg() bool

func (*PhysicalHashAgg) MemoryUsage

func (p *PhysicalHashAgg) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalHashAgg

func (*PhysicalHashAgg) ResolveIndices

func (p *PhysicalHashAgg) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalHashAgg) ToPB

func (p *PhysicalHashAgg) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalHashJoin

type PhysicalHashJoin struct {
	Concurrency     uint
	EqualConditions []*expression.ScalarFunction

	// null aware equal conditions
	NAEqualConditions []*expression.ScalarFunction

	// use the outer table to build a hash table when the outer table is smaller.
	UseOuterToBuild bool
	// contains filtered or unexported fields
}

PhysicalHashJoin represents hash join implementation of LogicalJoin.

func GetHashJoin

GetHashJoin is public for cascades planner.

func NewPhysicalHashJoin

func NewPhysicalHashJoin(p *logicalop.LogicalJoin, innerIdx int, useOuterToBuild bool, newStats *property.StatsInfo, prop ...*property.PhysicalProperty) *PhysicalHashJoin

NewPhysicalHashJoin creates a new PhysicalHashJoin from LogicalJoin.

func (*PhysicalHashJoin) Attach2Task

func (p *PhysicalHashJoin) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalHashJoin) CanUseHashJoinV2

func (p *PhysicalHashJoin) CanUseHashJoinV2() bool

CanUseHashJoinV2 returns true if current join is supported by hash join v2

func (*PhysicalHashJoin) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalHashJoin) CloneForPlanCache

func (op *PhysicalHashJoin) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalHashJoin) ExplainInfo

func (p *PhysicalHashJoin) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalHashJoin) ExplainNormalizedInfo

func (p *PhysicalHashJoin) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalHashJoin) ExtractCorrelatedCols

func (p *PhysicalHashJoin) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalHashJoin) GetCost

func (p *PhysicalHashJoin) GetCost(lCnt, rCnt float64, _ bool, costFlag uint64, op *optimizetrace.PhysicalOptimizeOp) float64

GetCost computes cost of hash join operator itself.

func (*PhysicalHashJoin) GetJoinType

func (p *PhysicalHashJoin) GetJoinType() logicalop.JoinType

func (*PhysicalHashJoin) GetPlanCostVer1

func (p *PhysicalHashJoin) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalHashJoin) GetPlanCostVer2

func (p *PhysicalHashJoin) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = build-child-cost + probe-child-cost + build-hash-cost + build-filter-cost + (probe-filter-cost + probe-hash-cost) / concurrency

func (PhysicalHashJoin) Init

Init initializes PhysicalHashJoin.

func (*PhysicalHashJoin) MemoryUsage

func (p *PhysicalHashJoin) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalHashJoin

func (*PhysicalHashJoin) PhysicalJoinImplement

func (*PhysicalHashJoin) PhysicalJoinImplement()

PhysicalJoinImplement implements base.PhysicalJoin interface.

func (*PhysicalHashJoin) ResolveIndices

func (p *PhysicalHashJoin) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalHashJoin) ResolveIndicesItself

func (p *PhysicalHashJoin) ResolveIndicesItself() (err error)

ResolveIndicesItself resolve indices for PhyicalPlan itself

func (*PhysicalHashJoin) RightIsBuildSide

func (p *PhysicalHashJoin) RightIsBuildSide() bool

RightIsBuildSide return true when right side is build side

func (*PhysicalHashJoin) ToPB

func (p *PhysicalHashJoin) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalIndexHashJoin

type PhysicalIndexHashJoin struct {
	PhysicalIndexJoin
	// KeepOuterOrder indicates whether keeping the output result order as the
	// outer side.
	KeepOuterOrder bool
}

PhysicalIndexHashJoin represents the plan of index look up hash join.

func (*PhysicalIndexHashJoin) Attach2Task

func (p *PhysicalIndexHashJoin) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalIndexHashJoin) CloneForPlanCache

func (op *PhysicalIndexHashJoin) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalIndexHashJoin) ExtractCorrelatedCols

func (p *PhysicalIndexHashJoin) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalIndexHashJoin) GetCost

func (p *PhysicalIndexHashJoin) GetCost(outerCnt, innerCnt, outerCost, innerCost float64, costFlag uint64) float64

GetCost computes the cost of index merge join operator and its children.

func (*PhysicalIndexHashJoin) GetJoinType

func (p *PhysicalIndexHashJoin) GetJoinType() logicalop.JoinType

func (*PhysicalIndexHashJoin) GetPlanCostVer1

func (p *PhysicalIndexHashJoin) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalIndexHashJoin) GetPlanCostVer2

GetPlanCostVer2 implements PhysicalPlan interface.

func (PhysicalIndexHashJoin) Init

Init initializes PhysicalIndexHashJoin.

func (*PhysicalIndexHashJoin) MemoryUsage

func (p *PhysicalIndexHashJoin) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalIndexHashJoin

func (*PhysicalIndexHashJoin) PhysicalJoinImplement

func (*PhysicalIndexHashJoin) PhysicalJoinImplement()

PhysicalJoinImplement implements base.PhysicalJoin interface.

type PhysicalIndexJoin

type PhysicalIndexJoin struct {

	// Ranges stores the IndexRanges when the inner plan is index scan.
	Ranges ranger.MutableRanges
	// KeyOff2IdxOff maps the offsets in join key to the offsets in the index.
	KeyOff2IdxOff []int
	// IdxColLens stores the length of each index column.
	IdxColLens []int
	// CompareFilters stores the filters for last column if those filters need to be evaluated during execution.
	// e.g. select * from t, t1 where t.a = t1.a and t.b > t1.b and t.b < t1.b+10
	//      If there's index(t.a, t.b). All the filters can be used to construct index range but t.b > t1.b and t.b < t1.b+10
	//      need to be evaluated after we fetch the data of t1.
	// This struct stores them and evaluate them to ranges.
	CompareFilters *ColWithCmpFuncManager
	// OuterHashKeys indicates the outer keys used to build hash table during
	// execution. OuterJoinKeys is the prefix of OuterHashKeys.
	OuterHashKeys []*expression.Column
	// InnerHashKeys indicates the inner keys used to build hash table during
	// execution. InnerJoinKeys is the prefix of InnerHashKeys.
	InnerHashKeys []*expression.Column
	// contains filtered or unexported fields
}

PhysicalIndexJoin represents the plan of index look up join.

func (*PhysicalIndexJoin) Attach2Task

func (p *PhysicalIndexJoin) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalIndexJoin) CloneForPlanCache

func (op *PhysicalIndexJoin) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalIndexJoin) ExplainInfo

func (p *PhysicalIndexJoin) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalIndexJoin) ExplainNormalizedInfo

func (p *PhysicalIndexJoin) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalIndexJoin) ExtractCorrelatedCols

func (p *PhysicalIndexJoin) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalIndexJoin) GetCost

func (p *PhysicalIndexJoin) GetCost(outerCnt, innerCnt, outerCost, innerCost float64, costFlag uint64) float64

GetCost computes the cost of index join operator and its children.

func (*PhysicalIndexJoin) GetJoinType

func (p *PhysicalIndexJoin) GetJoinType() logicalop.JoinType

func (*PhysicalIndexJoin) GetPlanCostVer1

func (p *PhysicalIndexJoin) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalIndexJoin) GetPlanCostVer2

func (p *PhysicalIndexJoin) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = build-child-cost + build-filter-cost + (probe-cost + probe-filter-cost) / concurrency probe-cost = probe-child-cost * build-rows / batchRatio

func (PhysicalIndexJoin) Init

Init initializes PhysicalIndexJoin.

func (*PhysicalIndexJoin) MemoryUsage

func (p *PhysicalIndexJoin) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalIndexJoin

func (*PhysicalIndexJoin) PhysicalJoinImplement

func (*PhysicalIndexJoin) PhysicalJoinImplement()

PhysicalJoinImplement implements base.PhysicalJoin interface.

func (*PhysicalIndexJoin) ResolveIndices

func (p *PhysicalIndexJoin) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

type PhysicalIndexLookUpReader

type PhysicalIndexLookUpReader struct {

	// IndexPlans flats the indexPlan to construct executor pb.
	IndexPlans []base.PhysicalPlan
	// TablePlans flats the tablePlan to construct executor pb.
	TablePlans []base.PhysicalPlan
	Paging     bool

	ExtraHandleCol *expression.Column
	// PushedLimit is used to avoid unnecessary table scan tasks of IndexLookUpReader.
	PushedLimit *PushedDownLimit

	CommonHandleCols []*expression.Column

	// Used by partition table.
	PlanPartInfo *PhysPlanPartInfo
	// contains filtered or unexported fields
}

PhysicalIndexLookUpReader is the index look up reader in tidb. It's used in case of double reading.

func (*PhysicalIndexLookUpReader) AppendChildCandidate

func (p *PhysicalIndexLookUpReader) AppendChildCandidate(op *optimizetrace.PhysicalOptimizeOp)

AppendChildCandidate implements PhysicalPlan interface.

func (*PhysicalIndexLookUpReader) BuildPlanTrace

func (p *PhysicalIndexLookUpReader) BuildPlanTrace() *tracing.PlanTrace

BuildPlanTrace implements op.PhysicalPlan interface.

func (*PhysicalIndexLookUpReader) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalIndexLookUpReader) CloneForPlanCache

func (op *PhysicalIndexLookUpReader) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalIndexLookUpReader) ExplainInfo

func (p *PhysicalIndexLookUpReader) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalIndexLookUpReader) ExtractCorrelatedCols

func (p *PhysicalIndexLookUpReader) ExtractCorrelatedCols() (corCols []*expression.CorrelatedColumn)

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalIndexLookUpReader) GetAvgTableRowSize

func (p *PhysicalIndexLookUpReader) GetAvgTableRowSize() float64

GetAvgTableRowSize return the average row size of each final row.

func (*PhysicalIndexLookUpReader) GetCost

func (p *PhysicalIndexLookUpReader) GetCost(costFlag uint64) (cost float64)

GetCost computes cost of index lookup operator itself.

func (*PhysicalIndexLookUpReader) GetIndexNetDataSize

func (p *PhysicalIndexLookUpReader) GetIndexNetDataSize() float64

GetIndexNetDataSize return the estimated total size in bytes via network transfer.

func (*PhysicalIndexLookUpReader) GetPlanCostVer1

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalIndexLookUpReader) GetPlanCostVer2

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = index-side-cost + (table-side-cost + double-read-cost) / double-read-concurrency index-side-cost = (index-child-cost + index-net-cost) / dist-concurrency # same with IndexReader table-side-cost = (table-child-cost + table-net-cost) / dist-concurrency # same with TableReader double-read-cost = double-read-request-cost + double-read-cpu-cost double-read-request-cost = double-read-tasks * request-factor double-read-cpu-cost = index-rows * cpu-factor double-read-tasks = index-rows / batch-size * task-per-batch # task-per-batch is a magic number now

func (PhysicalIndexLookUpReader) Init

Init initializes PhysicalIndexLookUpReader.

func (*PhysicalIndexLookUpReader) LoadTableStats

func (p *PhysicalIndexLookUpReader) LoadTableStats(ctx sessionctx.Context)

LoadTableStats preloads the stats data for the physical table

func (*PhysicalIndexLookUpReader) MemoryUsage

func (p *PhysicalIndexLookUpReader) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalIndexLookUpReader

func (*PhysicalIndexLookUpReader) ResolveIndices

func (p *PhysicalIndexLookUpReader) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalIndexLookUpReader) Schema

func (s *PhysicalIndexLookUpReader) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalIndexLookUpReader) SetSchema

func (s *PhysicalIndexLookUpReader) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalIndexMergeJoin

type PhysicalIndexMergeJoin struct {
	PhysicalIndexJoin

	// KeyOff2KeyOffOrderByIdx maps the offsets in join keys to the offsets in join keys order by index.
	KeyOff2KeyOffOrderByIdx []int
	// CompareFuncs store the compare functions for outer join keys and inner join key.
	CompareFuncs []expression.CompareFunc
	// OuterCompareFuncs store the compare functions for outer join keys and outer join
	// keys, it's for outer rows sort's convenience.
	OuterCompareFuncs []expression.CompareFunc
	// NeedOuterSort means whether outer rows should be sorted to build range.
	NeedOuterSort bool
	// Desc means whether inner child keep desc order.
	Desc bool
}

PhysicalIndexMergeJoin represents the plan of index look up merge join.

func (*PhysicalIndexMergeJoin) Attach2Task

func (p *PhysicalIndexMergeJoin) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalIndexMergeJoin) ExplainInfo

func (p *PhysicalIndexMergeJoin) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalIndexMergeJoin) ExplainNormalizedInfo

func (p *PhysicalIndexMergeJoin) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalIndexMergeJoin) ExtractCorrelatedCols

func (p *PhysicalIndexMergeJoin) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalIndexMergeJoin) GetCost

func (p *PhysicalIndexMergeJoin) GetCost(outerCnt, innerCnt, outerCost, innerCost float64, costFlag uint64) float64

GetCost computes the cost of index merge join operator and its children.

func (*PhysicalIndexMergeJoin) GetJoinType

func (p *PhysicalIndexMergeJoin) GetJoinType() logicalop.JoinType

func (*PhysicalIndexMergeJoin) GetPlanCostVer1

func (p *PhysicalIndexMergeJoin) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalIndexMergeJoin) GetPlanCostVer2

GetPlanCostVer2 implements PhysicalPlan interface.

func (PhysicalIndexMergeJoin) Init

Init initializes PhysicalIndexMergeJoin.

func (*PhysicalIndexMergeJoin) MemoryUsage

func (p *PhysicalIndexMergeJoin) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalIndexMergeJoin

func (*PhysicalIndexMergeJoin) PhysicalJoinImplement

func (*PhysicalIndexMergeJoin) PhysicalJoinImplement()

PhysicalJoinImplement implements base.PhysicalJoin interface.

type PhysicalIndexMergeReader

type PhysicalIndexMergeReader struct {

	// IsIntersectionType means whether it's intersection type or union type.
	// Intersection type is for expressions connected by `AND` and union type is for `OR`.
	IsIntersectionType bool
	// AccessMVIndex indicates whether this IndexMergeReader access a MVIndex.
	AccessMVIndex bool

	// PushedLimit is used to avoid unnecessary table scan tasks of IndexMergeReader.
	PushedLimit *PushedDownLimit
	// ByItems is used to support sorting the handles returned by partialPlans.
	ByItems []*util.ByItems

	// PartialPlans flats the partialPlans to construct executor pb.
	PartialPlans [][]base.PhysicalPlan
	// TablePlans flats the tablePlan to construct executor pb.
	TablePlans []base.PhysicalPlan

	// Used by partition table.
	PlanPartInfo *PhysPlanPartInfo

	KeepOrder bool

	HandleCols util.HandleCols
	// contains filtered or unexported fields
}

PhysicalIndexMergeReader is the reader using multiple indexes in tidb.

func (*PhysicalIndexMergeReader) AppendChildCandidate

func (p *PhysicalIndexMergeReader) AppendChildCandidate(op *optimizetrace.PhysicalOptimizeOp)

AppendChildCandidate implements PhysicalPlan interface.

func (*PhysicalIndexMergeReader) BuildPlanTrace

func (p *PhysicalIndexMergeReader) BuildPlanTrace() *tracing.PlanTrace

BuildPlanTrace implements op.PhysicalPlan interface.

func (*PhysicalIndexMergeReader) CloneForPlanCache

func (op *PhysicalIndexMergeReader) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalIndexMergeReader) ExplainInfo

func (p *PhysicalIndexMergeReader) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalIndexMergeReader) ExtractCorrelatedCols

func (p *PhysicalIndexMergeReader) ExtractCorrelatedCols() (corCols []*expression.CorrelatedColumn)

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalIndexMergeReader) GetAvgTableRowSize

func (p *PhysicalIndexMergeReader) GetAvgTableRowSize() float64

GetAvgTableRowSize return the average row size of table plan.

func (*PhysicalIndexMergeReader) GetPartialReaderNetDataSize

func (p *PhysicalIndexMergeReader) GetPartialReaderNetDataSize(plan base.PhysicalPlan) float64

GetPartialReaderNetDataSize returns the estimated total response data size of a partial read.

func (*PhysicalIndexMergeReader) GetPlanCostVer1

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalIndexMergeReader) GetPlanCostVer2

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = table-side-cost + sum(index-side-cost) index-side-cost = (index-child-cost + index-net-cost) / dist-concurrency # same with IndexReader table-side-cost = (table-child-cost + table-net-cost) / dist-concurrency # same with TableReader

func (PhysicalIndexMergeReader) Init

Init initializes PhysicalIndexMergeReader.

func (*PhysicalIndexMergeReader) LoadTableStats

func (p *PhysicalIndexMergeReader) LoadTableStats(ctx sessionctx.Context)

LoadTableStats preloads the stats data for the physical table

func (*PhysicalIndexMergeReader) MemoryUsage

func (p *PhysicalIndexMergeReader) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalIndexMergeReader

func (*PhysicalIndexMergeReader) ResolveIndices

func (p *PhysicalIndexMergeReader) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalIndexMergeReader) Schema

func (s *PhysicalIndexMergeReader) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalIndexMergeReader) SetSchema

func (s *PhysicalIndexMergeReader) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalIndexReader

type PhysicalIndexReader struct {
	IndexPlans []base.PhysicalPlan

	// OutputColumns represents the columns that index reader should return.
	OutputColumns []*expression.Column

	// Used by partition table.
	PlanPartInfo *PhysPlanPartInfo
	// contains filtered or unexported fields
}

PhysicalIndexReader is the index reader in tidb.

func GetPhysicalIndexReader

func GetPhysicalIndexReader(sg *logicalop.TiKVSingleGather, schema *expression.Schema, stats *property.StatsInfo, props ...*property.PhysicalProperty) *PhysicalIndexReader

GetPhysicalIndexReader returns PhysicalIndexReader for logical TiKVSingleGather.

func (*PhysicalIndexReader) AppendChildCandidate

func (p *PhysicalIndexReader) AppendChildCandidate(op *optimizetrace.PhysicalOptimizeOp)

AppendChildCandidate implements PhysicalPlan interface.

func (*PhysicalIndexReader) BuildPlanTrace

func (p *PhysicalIndexReader) BuildPlanTrace() *tracing.PlanTrace

BuildPlanTrace implements op.PhysicalPlan interface.

func (*PhysicalIndexReader) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalIndexReader) CloneForPlanCache

func (op *PhysicalIndexReader) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalIndexReader) ExplainInfo

func (p *PhysicalIndexReader) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalIndexReader) ExplainNormalizedInfo

func (p *PhysicalIndexReader) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalIndexReader) ExtractCorrelatedCols

func (p *PhysicalIndexReader) ExtractCorrelatedCols() (corCols []*expression.CorrelatedColumn)

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalIndexReader) GetNetDataSize

func (p *PhysicalIndexReader) GetNetDataSize() float64

GetNetDataSize calculates the cost of the plan in network data transfer.

func (*PhysicalIndexReader) GetPlanCostVer1

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalIndexReader) GetPlanCostVer2

func (p *PhysicalIndexReader) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = (child-cost + net-cost) / concurrency net-cost = rows * row-size * net-factor

func (PhysicalIndexReader) Init

Init initializes PhysicalIndexReader.

func (*PhysicalIndexReader) LoadTableStats

func (p *PhysicalIndexReader) LoadTableStats(ctx sessionctx.Context)

LoadTableStats preloads the stats data for the physical table

func (*PhysicalIndexReader) MemoryUsage

func (p *PhysicalIndexReader) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalIndexReader

func (*PhysicalIndexReader) ResolveIndices

func (p *PhysicalIndexReader) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalIndexReader) Schema

func (s *PhysicalIndexReader) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalIndexReader) SetChildren

func (p *PhysicalIndexReader) SetChildren(children ...base.PhysicalPlan)

SetChildren overrides op.PhysicalPlan SetChildren interface.

func (*PhysicalIndexReader) SetSchema

func (p *PhysicalIndexReader) SetSchema(_ *expression.Schema)

SetSchema overrides op.PhysicalPlan SetSchema interface.

type PhysicalIndexScan

type PhysicalIndexScan struct {

	// AccessCondition is used to calculate range.
	AccessCondition []expression.Expression

	Table      *model.TableInfo `plan-cache-clone:"shallow"` // please see comment on genPlanCloneForPlanCacheCode.
	Index      *model.IndexInfo `plan-cache-clone:"shallow"`
	IdxCols    []*expression.Column
	IdxColLens []int
	Ranges     []*ranger.Range     `plan-cache-clone:"shallow"`
	Columns    []*model.ColumnInfo `plan-cache-clone:"shallow"`
	DBName     pmodel.CIStr        `plan-cache-clone:"shallow"`

	TableAsName *pmodel.CIStr `plan-cache-clone:"shallow"`

	GenExprs map[model.TableItemID]expression.Expression `plan-cache-clone:"must-nil"`

	Desc      bool
	KeepOrder bool
	// ByItems only for partition table with orderBy + pushedLimit
	ByItems []*util.ByItems

	// DoubleRead means if the index executor will read kv two times.
	// If the query requires the columns that don't belong to index, DoubleRead will be true.
	DoubleRead bool

	NeedCommonHandle bool
	// contains filtered or unexported fields
}

PhysicalIndexScan represents an index scan plan.

func GetPhysicalIndexScan4LogicalIndexScan

func GetPhysicalIndexScan4LogicalIndexScan(s *logicalop.LogicalIndexScan, _ *expression.Schema, stats *property.StatsInfo) *PhysicalIndexScan

GetPhysicalIndexScan4LogicalIndexScan returns PhysicalIndexScan for the logical IndexScan.

func (*PhysicalIndexScan) AccessObject

func (p *PhysicalIndexScan) AccessObject() base.AccessObject

AccessObject implements dataAccesser interface.

func (*PhysicalIndexScan) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalIndexScan) CloneForPlanCache

func (op *PhysicalIndexScan) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalIndexScan) ExplainID

func (p *PhysicalIndexScan) ExplainID() fmt.Stringer

ExplainID overrides the ExplainID in order to match different range.

func (*PhysicalIndexScan) ExplainInfo

func (p *PhysicalIndexScan) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalIndexScan) ExplainNormalizedInfo

func (p *PhysicalIndexScan) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalIndexScan) ExtractCorrelatedCols

func (p *PhysicalIndexScan) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalIndexScan) GetPlanCostVer1

func (p *PhysicalIndexScan) GetPlanCostVer1(_ property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalIndexScan) GetPlanCostVer2

func (p *PhysicalIndexScan) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = rows * log2(row-size) * scan-factor log2(row-size) is from experiments.

func (PhysicalIndexScan) Init

Init initializes PhysicalIndexScan.

func (*PhysicalIndexScan) IsPartition

func (p *PhysicalIndexScan) IsPartition() (bool, int64)

IsPartition returns true and partition ID if it works on a partition.

func (*PhysicalIndexScan) IsPointGetByUniqueKey

func (p *PhysicalIndexScan) IsPointGetByUniqueKey(tc types.Context) bool

IsPointGetByUniqueKey checks whether is a point get by unique key.

func (*PhysicalIndexScan) MemoryUsage

func (p *PhysicalIndexScan) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalIndexScan

func (*PhysicalIndexScan) NeedExtraOutputCol

func (is *PhysicalIndexScan) NeedExtraOutputCol() bool

NeedExtraOutputCol is designed for check whether need an extra column for pid or physical table id when build indexReq.

func (*PhysicalIndexScan) OperatorInfo

func (p *PhysicalIndexScan) OperatorInfo(normalized bool) string

OperatorInfo implements dataAccesser interface.

func (*PhysicalIndexScan) ResolveIndices

func (p *PhysicalIndexScan) ResolveIndices() (err error)

func (*PhysicalIndexScan) Schema

func (s *PhysicalIndexScan) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalIndexScan) SetSchema

func (s *PhysicalIndexScan) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

func (*PhysicalIndexScan) TP

func (p *PhysicalIndexScan) TP() string

TP overrides the TP in order to match different range.

func (*PhysicalIndexScan) ToPB

func (p *PhysicalIndexScan) ToPB(_ *base.BuildPBContext, _ kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalJoin

type PhysicalJoin interface {
	base.PhysicalPlan
	PhysicalJoinImplement()

	GetJoinType() logicalop.JoinType
	// contains filtered or unexported methods
}

PhysicalJoin provides some common methods for join operators. Note that PhysicalApply is deliberately excluded from this interface.

type PhysicalLimit

type PhysicalLimit struct {
	PartitionBy []property.SortItem
	Offset      uint64
	Count       uint64
	// contains filtered or unexported fields
}

PhysicalLimit is the physical operator of Limit.

func (*PhysicalLimit) Attach2Task

func (p *PhysicalLimit) Attach2Task(tasks ...base.Task) base.Task

Attach2Task attach limit to different cases. For Normal Index Lookup 1: attach the limit to table side or index side of normal index lookup cop task. (normal case, old code, no more explanation here)

For Index Merge: 2: attach the limit to **table** side for index merge intersection case, cause intersection will invalidate the fetched limit+offset rows from each partial index plan, you can not decide how many you want in advance for partial index path, actually. After we sink limit to table side, we still need an upper root limit to control the real limit count admission.

3: attach the limit to **index** side for index merge union case, because each index plan will output the fetched limit+offset (* N path) rows, you still need an embedded pushedLimit inside index merge reader to cut it down.

4: attach the limit to the TOP of root index merge operator if there is some root condition exists for index merge intersection/union case.

func (*PhysicalLimit) Clone

func (p *PhysicalLimit) Clone(newCtx base.PlanContext) (base.PhysicalPlan, error)

Clone implements op.PhysicalPlan interface.

func (*PhysicalLimit) CloneForPlanCache

func (op *PhysicalLimit) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalLimit) ExplainInfo

func (p *PhysicalLimit) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalLimit) GetPartitionBy

func (p *PhysicalLimit) GetPartitionBy() []property.SortItem

GetPartitionBy returns partition by fields

func (PhysicalLimit) Init

func (p PhysicalLimit) Init(ctx base.PlanContext, stats *property.StatsInfo, offset int, props ...*property.PhysicalProperty) *PhysicalLimit

Init initializes PhysicalLimit.

func (*PhysicalLimit) MemoryUsage

func (p *PhysicalLimit) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalLimit

func (*PhysicalLimit) ResolveIndices

func (p *PhysicalLimit) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalLimit) Schema

func (s *PhysicalLimit) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalLimit) SetSchema

func (s *PhysicalLimit) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

func (*PhysicalLimit) ToPB

func (p *PhysicalLimit) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalLock

type PhysicalLock struct {
	physicalop.BasePhysicalPlan

	Lock *ast.SelectLockInfo `plan-cache-clone:"shallow"`

	TblID2Handle       map[int64][]util.HandleCols
	TblID2PhysTblIDCol map[int64]*expression.Column
}

PhysicalLock is the physical operator of lock, which is used for `select ... for update` clause.

func (*PhysicalLock) CloneForPlanCache

func (op *PhysicalLock) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalLock) ExplainInfo

func (p *PhysicalLock) ExplainInfo() string

ExplainInfo implements Plan interface.

func (PhysicalLock) Init

Init initializes PhysicalLock.

func (*PhysicalLock) MemoryUsage

func (pl *PhysicalLock) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalLock

func (*PhysicalLock) ResolveIndices

func (p *PhysicalLock) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

type PhysicalMaxOneRow

type PhysicalMaxOneRow struct {
	physicalop.BasePhysicalPlan
}

PhysicalMaxOneRow is the physical operator of maxOneRow.

func (*PhysicalMaxOneRow) Clone

Clone implements op.PhysicalPlan interface.

func (PhysicalMaxOneRow) Init

Init initializes PhysicalMaxOneRow.

func (*PhysicalMaxOneRow) MemoryUsage

func (p *PhysicalMaxOneRow) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalMaxOneRow

type PhysicalMemTable

type PhysicalMemTable struct {
	DBName         pmodel.CIStr
	Table          *model.TableInfo
	Columns        []*model.ColumnInfo
	Extractor      base.MemTablePredicateExtractor
	QueryTimeRange util.QueryTimeRange
	// contains filtered or unexported fields
}

PhysicalMemTable reads memory table.

func (*PhysicalMemTable) AccessObject

func (p *PhysicalMemTable) AccessObject() base.AccessObject

AccessObject implements dataAccesser interface.

func (*PhysicalMemTable) ExplainInfo

func (p *PhysicalMemTable) ExplainInfo() string

ExplainInfo implements Plan interface.

func (PhysicalMemTable) Init

Init initializes PhysicalMemTable.

func (*PhysicalMemTable) MemoryUsage

func (p *PhysicalMemTable) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalMemTable

func (*PhysicalMemTable) OperatorInfo

func (p *PhysicalMemTable) OperatorInfo(_ bool) string

OperatorInfo implements dataAccesser interface.

func (*PhysicalMemTable) ResolveIndices

func (p *PhysicalMemTable) ResolveIndices() (err error)

func (*PhysicalMemTable) Schema

func (s *PhysicalMemTable) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalMemTable) SetSchema

func (s *PhysicalMemTable) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalMergeJoin

type PhysicalMergeJoin struct {
	CompareFuncs []expression.CompareFunc `plan-cache-clone:"shallow"`
	// Desc means whether inner child keep desc order.
	Desc bool
	// contains filtered or unexported fields
}

PhysicalMergeJoin represents merge join implementation of LogicalJoin.

func BuildMergeJoinPlan

func BuildMergeJoinPlan(ctx base.PlanContext, joinType logicalop.JoinType, leftKeys, rightKeys []*expression.Column) *PhysicalMergeJoin

BuildMergeJoinPlan builds a PhysicalMergeJoin from the given fields. Currently, it is only used for test purpose.

func (*PhysicalMergeJoin) Attach2Task

func (p *PhysicalMergeJoin) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalMergeJoin) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalMergeJoin) CloneForPlanCache

func (op *PhysicalMergeJoin) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalMergeJoin) ExplainInfo

func (p *PhysicalMergeJoin) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalMergeJoin) ExplainNormalizedInfo

func (p *PhysicalMergeJoin) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalMergeJoin) ExtractCorrelatedCols

func (p *PhysicalMergeJoin) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalMergeJoin) GetCost

func (p *PhysicalMergeJoin) GetCost(lCnt, rCnt float64, costFlag uint64) float64

GetCost computes cost of merge join operator itself.

func (*PhysicalMergeJoin) GetJoinType

func (p *PhysicalMergeJoin) GetJoinType() logicalop.JoinType

func (*PhysicalMergeJoin) GetPlanCostVer1

func (p *PhysicalMergeJoin) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalMergeJoin) GetPlanCostVer2

func (p *PhysicalMergeJoin) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = left-child-cost + right-child-cost + filter-cost + group-cost

func (PhysicalMergeJoin) Init

Init initializes PhysicalMergeJoin.

func (*PhysicalMergeJoin) MemoryUsage

func (p *PhysicalMergeJoin) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalMergeJoin

func (*PhysicalMergeJoin) PhysicalJoinImplement

func (*PhysicalMergeJoin) PhysicalJoinImplement()

PhysicalJoinImplement implements base.PhysicalJoin interface.

func (*PhysicalMergeJoin) ResolveIndices

func (p *PhysicalMergeJoin) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

type PhysicalProjection

type PhysicalProjection struct {
	Exprs            []expression.Expression
	CalculateNoDelay bool

	// AvoidColumnEvaluator is ONLY used to avoid building columnEvaluator
	// for the expressions of Projection which is child of Union operator.
	// Related issue: TiDB#8141(https://github.com/pingcap/tidb/issues/8141)
	AvoidColumnEvaluator bool
	// contains filtered or unexported fields
}

PhysicalProjection is the physical operator of projection.

func (*PhysicalProjection) Attach2Task

func (p *PhysicalProjection) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalProjection) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalProjection) CloneForPlanCache

func (op *PhysicalProjection) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalProjection) ExplainInfo

func (p *PhysicalProjection) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalProjection) ExplainNormalizedInfo

func (p *PhysicalProjection) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalProjection) ExtractCorrelatedCols

func (p *PhysicalProjection) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalProjection) GetCost

func (p *PhysicalProjection) GetCost(count float64) float64

GetCost computes the cost of projection operator itself.

func (*PhysicalProjection) GetPlanCostVer1

func (p *PhysicalProjection) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalProjection) GetPlanCostVer2

func (p *PhysicalProjection) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = child-cost + proj-cost / concurrency proj-cost = input-rows * len(expressions) * cpu-factor

func (PhysicalProjection) Init

Init initializes PhysicalProjection.

func (*PhysicalProjection) MemoryUsage

func (p *PhysicalProjection) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalProjection

func (*PhysicalProjection) ResolveIndices

func (p *PhysicalProjection) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalProjection) ResolveIndicesItself

func (p *PhysicalProjection) ResolveIndicesItself() (err error)

ResolveIndicesItself resolve indices for PhysicalPlan itself

func (*PhysicalProjection) Schema

func (s *PhysicalProjection) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalProjection) SetSchema

func (s *PhysicalProjection) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

func (*PhysicalProjection) ToPB

func (p *PhysicalProjection) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalSelection

type PhysicalSelection struct {
	physicalop.BasePhysicalPlan

	Conditions []expression.Expression
	// contains filtered or unexported fields
}

PhysicalSelection represents a filter.

func (*PhysicalSelection) Attach2Task

func (sel *PhysicalSelection) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalSelection) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalSelection) CloneForPlanCache

func (op *PhysicalSelection) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalSelection) ExplainInfo

func (p *PhysicalSelection) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalSelection) ExplainNormalizedInfo

func (p *PhysicalSelection) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalSelection) ExtractCorrelatedCols

func (p *PhysicalSelection) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalSelection) GetPlanCostVer1

func (p *PhysicalSelection) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalSelection) GetPlanCostVer2

func (p *PhysicalSelection) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = child-cost + filter-cost

func (PhysicalSelection) Init

Init initializes PhysicalSelection.

func (*PhysicalSelection) MemoryUsage

func (p *PhysicalSelection) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalSelection

func (*PhysicalSelection) ResolveIndices

func (p *PhysicalSelection) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalSelection) ToPB

func (p *PhysicalSelection) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalSequence

type PhysicalSequence struct {
	// contains filtered or unexported fields
}

PhysicalSequence is the physical representation of LogicalSequence. Used to mark the CTE producers in the plan tree.

func (*PhysicalSequence) Attach2Task

func (p *PhysicalSequence) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements the PhysicalPlan interface.

func (*PhysicalSequence) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalSequence) ExplainID

func (p *PhysicalSequence) ExplainID() fmt.Stringer

ExplainID overrides the ExplainID.

func (*PhysicalSequence) ExplainInfo

func (*PhysicalSequence) ExplainInfo() string

ExplainInfo overrides the ExplainInfo.

func (PhysicalSequence) Init

func (p PhysicalSequence) Init(ctx base.PlanContext, stats *property.StatsInfo, blockOffset int, props ...*property.PhysicalProperty) *PhysicalSequence

Init initializes PhysicalSequence

func (*PhysicalSequence) MemoryUsage

func (p *PhysicalSequence) MemoryUsage() (sum int64)

MemoryUsage returns the memory usage of the PhysicalSequence.

func (*PhysicalSequence) ResolveIndices

func (p *PhysicalSequence) ResolveIndices() (err error)

func (*PhysicalSequence) Schema

func (p *PhysicalSequence) Schema() *expression.Schema

Schema returns its last child(which is the main query tree)'s schema.

func (*PhysicalSequence) SetSchema

func (s *PhysicalSequence) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalShow

type PhysicalShow struct {
	logicalop.ShowContents

	Extractor base.ShowPredicateExtractor
	// contains filtered or unexported fields
}

PhysicalShow represents a show plan.

func (PhysicalShow) Init

Init initializes PhysicalShow.

func (*PhysicalShow) MemoryUsage

func (p *PhysicalShow) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalShow

func (*PhysicalShow) ResolveIndices

func (p *PhysicalShow) ResolveIndices() (err error)

func (*PhysicalShow) Schema

func (s *PhysicalShow) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalShow) SetSchema

func (s *PhysicalShow) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalShowDDLJobs

type PhysicalShowDDLJobs struct {
	JobNumber int64
	// contains filtered or unexported fields
}

PhysicalShowDDLJobs is for showing DDL job list.

func (PhysicalShowDDLJobs) Init

Init initializes PhysicalShowDDLJobs.

func (*PhysicalShowDDLJobs) MemoryUsage

func (p *PhysicalShowDDLJobs) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalShowDDLJobs

func (*PhysicalShowDDLJobs) ResolveIndices

func (p *PhysicalShowDDLJobs) ResolveIndices() (err error)

func (*PhysicalShowDDLJobs) Schema

func (s *PhysicalShowDDLJobs) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalShowDDLJobs) SetSchema

func (s *PhysicalShowDDLJobs) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalShuffle

type PhysicalShuffle struct {
	physicalop.BasePhysicalPlan

	Concurrency int
	Tails       []base.PhysicalPlan
	DataSources []base.PhysicalPlan

	SplitterType PartitionSplitterType
	ByItemArrays [][]expression.Expression
}

PhysicalShuffle represents a shuffle plan. `Tails` and `DataSources` are the last plan within and the first plan following the "shuffle", respectively,

to build the child executors chain.

Take `Window` operator for example:

Shuffle -> Window -> Sort -> DataSource, will be separated into:
  ==> Shuffle: for main thread
  ==> Window -> Sort(:Tail) -> shuffleWorker: for workers
  ==> DataSource: for `fetchDataAndSplit` thread

func (*PhysicalShuffle) ExplainInfo

func (p *PhysicalShuffle) ExplainInfo() string

ExplainInfo implements Plan interface.

func (PhysicalShuffle) Init

Init initializes PhysicalShuffle.

func (*PhysicalShuffle) MemoryUsage

func (p *PhysicalShuffle) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalShuffle

func (*PhysicalShuffle) ResolveIndices

func (p *PhysicalShuffle) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

type PhysicalShuffleReceiverStub

type PhysicalShuffleReceiverStub struct {

	// Receiver points to `executor.shuffleReceiver`.
	Receiver unsafe.Pointer
	// DataSource is the op.PhysicalPlan of the Receiver.
	DataSource base.PhysicalPlan
	// contains filtered or unexported fields
}

PhysicalShuffleReceiverStub represents a receiver stub of `PhysicalShuffle`, and actually, is executed by `executor.shuffleWorker`.

func (PhysicalShuffleReceiverStub) Init

Init initializes PhysicalShuffleReceiverStub.

func (*PhysicalShuffleReceiverStub) MemoryUsage

func (p *PhysicalShuffleReceiverStub) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalShuffleReceiverStub

func (*PhysicalShuffleReceiverStub) ResolveIndices

func (p *PhysicalShuffleReceiverStub) ResolveIndices() (err error)

func (*PhysicalShuffleReceiverStub) Schema

func (s *PhysicalShuffleReceiverStub) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalShuffleReceiverStub) SetSchema

func (s *PhysicalShuffleReceiverStub) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalSimpleWrapper

type PhysicalSimpleWrapper struct {
	physicalop.BasePhysicalPlan
	Inner Simple
}

PhysicalSimpleWrapper is a wrapper of `Simple` to implement physical plan interface.

Used for simple statements executing in coprocessor.

func (*PhysicalSimpleWrapper) MemoryUsage

func (p *PhysicalSimpleWrapper) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalSimpleWrapper

type PhysicalSort

type PhysicalSort struct {
	physicalop.BasePhysicalPlan

	ByItems []*util.ByItems
	// whether this operator only need to sort the data of one partition.
	// it is true only if it is used to sort the sharded data of the window function.
	IsPartialSort bool
}

PhysicalSort is the physical operator of sort, which implements a memory sort.

func (*PhysicalSort) Attach2Task

func (p *PhysicalSort) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalSort) Clone

func (ls *PhysicalSort) Clone(newCtx base.PlanContext) (base.PhysicalPlan, error)

Clone implements op.PhysicalPlan interface.

func (*PhysicalSort) CloneForPlanCache

func (op *PhysicalSort) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalSort) ExplainInfo

func (p *PhysicalSort) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalSort) ExtractCorrelatedCols

func (ls *PhysicalSort) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalSort) GetCost

func (p *PhysicalSort) GetCost(count float64, schema *expression.Schema) float64

GetCost computes the cost of in memory sort.

func (*PhysicalSort) GetPlanCostVer1

func (p *PhysicalSort) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalSort) GetPlanCostVer2

func (p *PhysicalSort) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = child-cost + sort-cpu-cost + sort-mem-cost + sort-disk-cost sort-cpu-cost = rows * log2(rows) * len(sort-items) * cpu-factor if no spill: 1. sort-mem-cost = rows * row-size * mem-factor 2. sort-disk-cost = 0 else if spill: 1. sort-mem-cost = mem-quota * mem-factor 2. sort-disk-cost = rows * row-size * disk-factor

func (PhysicalSort) Init

func (p PhysicalSort) Init(ctx base.PlanContext, stats *property.StatsInfo, offset int, props ...*property.PhysicalProperty) *PhysicalSort

Init initializes PhysicalSort.

func (*PhysicalSort) MemoryUsage

func (ls *PhysicalSort) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalSort

func (*PhysicalSort) ResolveIndices

func (p *PhysicalSort) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalSort) ToPB

func (p *PhysicalSort) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalStreamAgg

type PhysicalStreamAgg struct {
	// contains filtered or unexported fields
}

PhysicalStreamAgg is stream operator of aggregate.

func (*PhysicalStreamAgg) Attach2Task

func (p *PhysicalStreamAgg) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalStreamAgg) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalStreamAgg) CloneForPlanCache

func (op *PhysicalStreamAgg) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalStreamAgg) ExplainInfo

func (p *PhysicalStreamAgg) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalStreamAgg) ExplainNormalizedInfo

func (p *PhysicalStreamAgg) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalStreamAgg) ExtractCorrelatedCols

func (p *PhysicalStreamAgg) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalStreamAgg) GetCost

func (p *PhysicalStreamAgg) GetCost(inputRows float64, isRoot, _ bool, costFlag uint64) float64

GetCost computes cost of stream aggregation considering CPU/memory.

func (*PhysicalStreamAgg) GetPlanCostVer1

func (p *PhysicalStreamAgg) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalStreamAgg) GetPlanCostVer2

func (p *PhysicalStreamAgg) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = child-cost + agg-cost + group-cost

func (PhysicalStreamAgg) Init

func (base PhysicalStreamAgg) Init(ctx base.PlanContext, stats *property.StatsInfo, offset int) *basePhysicalAgg

Init initializes basePhysicalAgg.

func (*PhysicalStreamAgg) IsFinalAgg

func (p *PhysicalStreamAgg) IsFinalAgg() bool

func (*PhysicalStreamAgg) MemoryUsage

func (p *PhysicalStreamAgg) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalStreamAgg

func (*PhysicalStreamAgg) ResolveIndices

func (p *PhysicalStreamAgg) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalStreamAgg) ToPB

func (p *PhysicalStreamAgg) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalTableDual

type PhysicalTableDual struct {
	RowCount int
	// contains filtered or unexported fields
}

PhysicalTableDual is the physical operator of dual.

func (*PhysicalTableDual) ExplainInfo

func (p *PhysicalTableDual) ExplainInfo() string

ExplainInfo implements Plan interface.

func (PhysicalTableDual) Init

Init initializes PhysicalTableDual.

func (*PhysicalTableDual) MemoryUsage

func (p *PhysicalTableDual) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalTableDual

func (*PhysicalTableDual) OutputNames

func (p *PhysicalTableDual) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*PhysicalTableDual) ResolveIndices

func (p *PhysicalTableDual) ResolveIndices() (err error)

func (*PhysicalTableDual) Schema

func (s *PhysicalTableDual) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalTableDual) SetOutputNames

func (p *PhysicalTableDual) SetOutputNames(names types.NameSlice)

SetOutputNames sets the outputting name by the given slice.

func (*PhysicalTableDual) SetSchema

func (s *PhysicalTableDual) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalTableReader

type PhysicalTableReader struct {
	TablePlans []base.PhysicalPlan

	// StoreType indicates table read from which type of store.
	StoreType kv.StoreType

	// ReadReqType is the read request type for current physical table reader, there are 3 kinds of read request: Cop,
	// BatchCop and MPP, currently, the latter two are only used in TiFlash
	ReadReqType ReadReqType

	IsCommonHandle bool

	// Used by partition table.
	PlanPartInfo *PhysPlanPartInfo
	// Used by MPP, because MPP plan may contain join/union/union all, it is possible that a physical table reader contains more than 1 table scan
	TableScanAndPartitionInfos []tableScanAndPartitionInfo `plan-cache-clone:"must-nil"`
	// contains filtered or unexported fields
}

PhysicalTableReader is the table reader in tidb.

func GetPhysicalTableReader

func GetPhysicalTableReader(sg *logicalop.TiKVSingleGather, schema *expression.Schema, stats *property.StatsInfo, props ...*property.PhysicalProperty) *PhysicalTableReader

GetPhysicalTableReader returns PhysicalTableReader for logical TiKVSingleGather.

func (*PhysicalTableReader) AppendChildCandidate

func (p *PhysicalTableReader) AppendChildCandidate(op *optimizetrace.PhysicalOptimizeOp)

AppendChildCandidate implements PhysicalPlan interface.

func (*PhysicalTableReader) BuildPlanTrace

func (p *PhysicalTableReader) BuildPlanTrace() *tracing.PlanTrace

BuildPlanTrace implements op.PhysicalPlan interface.

func (*PhysicalTableReader) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalTableReader) CloneForPlanCache

func (op *PhysicalTableReader) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalTableReader) ExplainInfo

func (p *PhysicalTableReader) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalTableReader) ExplainNormalizedInfo

func (*PhysicalTableReader) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalTableReader) ExtractCorrelatedCols

func (p *PhysicalTableReader) ExtractCorrelatedCols() (corCols []*expression.CorrelatedColumn)

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalTableReader) GetAvgRowSize

func (p *PhysicalTableReader) GetAvgRowSize() float64

GetAvgRowSize return the average row size of this plan.

func (*PhysicalTableReader) GetNetDataSize

func (p *PhysicalTableReader) GetNetDataSize() float64

GetNetDataSize calculates the estimated total data size fetched from storage.

func (*PhysicalTableReader) GetPlanCostVer1

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalTableReader) GetPlanCostVer2

func (p *PhysicalTableReader) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = (child-cost + net-cost) / concurrency net-cost = rows * row-size * net-factor

func (*PhysicalTableReader) GetTablePlan

func (p *PhysicalTableReader) GetTablePlan() base.PhysicalPlan

GetTablePlan exports the tablePlan.

func (*PhysicalTableReader) GetTableScan

func (p *PhysicalTableReader) GetTableScan() (*PhysicalTableScan, error)

GetTableScan exports the tableScan that contained in tablePlans and return error when the count of table scan != 1.

func (*PhysicalTableReader) GetTableScans

func (p *PhysicalTableReader) GetTableScans() []*PhysicalTableScan

GetTableScans exports the tableScan that contained in tablePlans.

func (PhysicalTableReader) Init

Init initializes PhysicalTableReader.

func (*PhysicalTableReader) LoadTableStats

func (p *PhysicalTableReader) LoadTableStats(ctx sessionctx.Context)

LoadTableStats loads the stats of the table read by this plan.

func (*PhysicalTableReader) MemoryUsage

func (p *PhysicalTableReader) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalTableReader

func (*PhysicalTableReader) OperatorInfo

func (p *PhysicalTableReader) OperatorInfo(_ bool) string

OperatorInfo return other operator information to be explained.

func (*PhysicalTableReader) ResolveIndices

func (p *PhysicalTableReader) ResolveIndices() error

ResolveIndices implements Plan interface.

func (*PhysicalTableReader) Schema

func (s *PhysicalTableReader) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalTableReader) SetChildren

func (p *PhysicalTableReader) SetChildren(children ...base.PhysicalPlan)

SetChildren overrides op.PhysicalPlan SetChildren interface.

func (*PhysicalTableReader) SetSchema

func (s *PhysicalTableReader) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

func (*PhysicalTableReader) SetTablePlanForTest

func (p *PhysicalTableReader) SetTablePlanForTest(pp base.PhysicalPlan)

SetTablePlanForTest sets tablePlan field for test usage only

type PhysicalTableSample

type PhysicalTableSample struct {
	TableSampleInfo *tablesampler.TableSampleInfo
	TableInfo       table.Table
	PhysicalTableID int64
	Desc            bool
	// contains filtered or unexported fields
}

PhysicalTableSample represents a table sample plan. It returns the sample rows to its parent operand.

func (PhysicalTableSample) Init

Init initializes PhysicalTableSample.

func (*PhysicalTableSample) MemoryUsage

func (p *PhysicalTableSample) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalTableSample

func (*PhysicalTableSample) ResolveIndices

func (p *PhysicalTableSample) ResolveIndices() (err error)

func (*PhysicalTableSample) Schema

func (s *PhysicalTableSample) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalTableSample) SetSchema

func (s *PhysicalTableSample) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalTableScan

type PhysicalTableScan struct {

	// AccessCondition is used to calculate range.
	AccessCondition []expression.Expression

	// LateMaterializationFilterCondition is used to record the filter conditions
	// that are pushed down to table scan from selection by late materialization.
	// TODO: remove this field after we support pushing down selection to coprocessor.
	LateMaterializationFilterCondition []expression.Expression

	Table   *model.TableInfo    `plan-cache-clone:"shallow"`
	Columns []*model.ColumnInfo `plan-cache-clone:"shallow"`
	DBName  pmodel.CIStr        `plan-cache-clone:"shallow"`
	Ranges  []*ranger.Range     `plan-cache-clone:"shallow"`

	TableAsName *pmodel.CIStr `plan-cache-clone:"shallow"`

	// HandleIdx is the index of handle, which is only used for admin check table.
	HandleIdx  []int
	HandleCols util.HandleCols

	StoreType kv.StoreType

	IsMPPOrBatchCop bool // Used for tiflash PartitionTableScan.

	// KeepOrder is true, if sort data by scanning pkcol,
	KeepOrder bool
	Desc      bool
	// ByItems only for partition table with orderBy + pushedLimit
	ByItems []*util.ByItems

	PlanPartInfo *PhysPlanPartInfo

	SampleInfo *tablesampler.TableSampleInfo `plan-cache-clone:"must-nil"`

	AnnIndexExtra *VectorIndexExtra `plan-cache-clone:"must-nil"` // MPP plan should not be cached.
	// contains filtered or unexported fields
}

PhysicalTableScan represents a table scan plan.

func GetPhysicalScan4LogicalTableScan

func GetPhysicalScan4LogicalTableScan(s *logicalop.LogicalTableScan, schema *expression.Schema, stats *property.StatsInfo) *PhysicalTableScan

GetPhysicalScan4LogicalTableScan returns PhysicalTableScan for the LogicalTableScan.

func (*PhysicalTableScan) AccessObject

func (p *PhysicalTableScan) AccessObject() base.AccessObject

AccessObject implements dataAccesser interface.

func (*PhysicalTableScan) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalTableScan) CloneForPlanCache

func (op *PhysicalTableScan) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalTableScan) ExplainID

func (p *PhysicalTableScan) ExplainID() fmt.Stringer

ExplainID overrides the ExplainID in order to match different range.

func (*PhysicalTableScan) ExplainInfo

func (p *PhysicalTableScan) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalTableScan) ExplainNormalizedInfo

func (p *PhysicalTableScan) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalTableScan) ExtractCorrelatedCols

func (ts *PhysicalTableScan) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalTableScan) GetPlanCostVer1

func (p *PhysicalTableScan) GetPlanCostVer1(_ property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalTableScan) GetPlanCostVer2

func (p *PhysicalTableScan) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = rows * log2(row-size) * scan-factor log2(row-size) is from experiments.

func (PhysicalTableScan) Init

Init initializes PhysicalTableScan.

func (*PhysicalTableScan) IsPartition

func (ts *PhysicalTableScan) IsPartition() (bool, int64)

IsPartition returns true and partition ID if it's actually a partition.

func (*PhysicalTableScan) MemoryUsage

func (ts *PhysicalTableScan) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalTableScan

func (*PhysicalTableScan) OperatorInfo

func (p *PhysicalTableScan) OperatorInfo(normalized bool) string

OperatorInfo implements dataAccesser interface.

func (*PhysicalTableScan) ResolveCorrelatedColumns

func (ts *PhysicalTableScan) ResolveCorrelatedColumns() ([]*ranger.Range, error)

ResolveCorrelatedColumns resolves the correlated columns in range access. We already limit range mem usage when building ranges in optimizer phase, so we don't need and shouldn't limit range mem usage when rebuilding ranges during the execution phase.

func (*PhysicalTableScan) ResolveIndices

func (p *PhysicalTableScan) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalTableScan) ResolveIndicesItself

func (p *PhysicalTableScan) ResolveIndicesItself() (err error)

ResolveIndicesItself implements PhysicalTableScan interface.

func (*PhysicalTableScan) Schema

func (s *PhysicalTableScan) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalTableScan) SetIsChildOfIndexLookUp

func (ts *PhysicalTableScan) SetIsChildOfIndexLookUp(isIsChildOfIndexLookUp bool)

SetIsChildOfIndexLookUp is to set the bool if is a child of IndexLookUpReader

func (*PhysicalTableScan) SetSchema

func (s *PhysicalTableScan) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

func (*PhysicalTableScan) TP

func (p *PhysicalTableScan) TP() string

TP overrides the TP in order to match different range.

func (*PhysicalTableScan) ToPB

func (p *PhysicalTableScan) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalTopN

type PhysicalTopN struct {
	physicalop.BasePhysicalPlan

	ByItems     []*util.ByItems
	PartitionBy []property.SortItem
	Offset      uint64
	Count       uint64
}

PhysicalTopN is the physical operator of topN.

func (*PhysicalTopN) Attach2Task

func (p *PhysicalTopN) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements physical plan

func (*PhysicalTopN) Clone

func (lt *PhysicalTopN) Clone(newCtx base.PlanContext) (base.PhysicalPlan, error)

Clone implements op.PhysicalPlan interface.

func (*PhysicalTopN) CloneForPlanCache

func (op *PhysicalTopN) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalTopN) ExplainInfo

func (p *PhysicalTopN) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalTopN) ExplainNormalizedInfo

func (p *PhysicalTopN) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PhysicalTopN) ExtractCorrelatedCols

func (lt *PhysicalTopN) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (*PhysicalTopN) GetCost

func (p *PhysicalTopN) GetCost(count float64, isRoot bool) float64

GetCost computes cost of TopN operator itself.

func (*PhysicalTopN) GetPartitionBy

func (lt *PhysicalTopN) GetPartitionBy() []property.SortItem

GetPartitionBy returns partition by fields

func (*PhysicalTopN) GetPlanCostVer1

func (p *PhysicalTopN) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalTopN) GetPlanCostVer2

func (p *PhysicalTopN) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is: plan-cost = child-cost + topn-cpu-cost + topn-mem-cost topn-cpu-cost = rows * log2(N) * len(sort-items) * cpu-factor topn-mem-cost = N * row-size * mem-factor

func (PhysicalTopN) Init

func (p PhysicalTopN) Init(ctx base.PlanContext, stats *property.StatsInfo, offset int, props ...*property.PhysicalProperty) *PhysicalTopN

Init initializes PhysicalTopN.

func (*PhysicalTopN) MemoryUsage

func (lt *PhysicalTopN) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalTopN

func (*PhysicalTopN) ResolveIndices

func (p *PhysicalTopN) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalTopN) ToPB

func (p *PhysicalTopN) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PhysicalUnionAll

type PhysicalUnionAll struct {
	// contains filtered or unexported fields
}

PhysicalUnionAll is the physical operator of UnionAll.

func (*PhysicalUnionAll) Attach2Task

func (p *PhysicalUnionAll) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalUnionAll) Clone

Clone implements op.PhysicalPlan interface.

func (*PhysicalUnionAll) CloneForPlanCache

func (op *PhysicalUnionAll) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalUnionAll) GetPlanCostVer1

func (p *PhysicalUnionAll) GetPlanCostVer1(taskType property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PhysicalUnionAll) GetPlanCostVer2

func (p *PhysicalUnionAll) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 calculates the cost of the plan if it has not been calculated yet and returns the cost. plan-cost = sum(child-cost) / concurrency

func (PhysicalUnionAll) Init

Init initializes PhysicalUnionAll.

func (*PhysicalUnionAll) MemoryUsage

func (p *PhysicalUnionAll) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalUnionAll

func (*PhysicalUnionAll) ResolveIndices

func (p *PhysicalUnionAll) ResolveIndices() (err error)

func (*PhysicalUnionAll) Schema

func (s *PhysicalUnionAll) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalUnionAll) SetSchema

func (s *PhysicalUnionAll) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PhysicalUnionScan

type PhysicalUnionScan struct {
	physicalop.BasePhysicalPlan

	Conditions []expression.Expression

	HandleCols util.HandleCols
}

PhysicalUnionScan represents a union scan operator.

func (*PhysicalUnionScan) Attach2Task

func (p *PhysicalUnionScan) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements PhysicalPlan interface.

func (*PhysicalUnionScan) CloneForPlanCache

func (op *PhysicalUnionScan) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PhysicalUnionScan) ExplainInfo

func (p *PhysicalUnionScan) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalUnionScan) ExtractCorrelatedCols

func (p *PhysicalUnionScan) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (PhysicalUnionScan) Init

Init initializes PhysicalUnionScan.

func (*PhysicalUnionScan) MemoryUsage

func (p *PhysicalUnionScan) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalUnionScan

func (*PhysicalUnionScan) ResolveIndices

func (p *PhysicalUnionScan) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

type PhysicalWindow

type PhysicalWindow struct {
	WindowFuncDescs []*aggregation.WindowFuncDesc
	PartitionBy     []property.SortItem
	OrderBy         []property.SortItem
	Frame           *logicalop.WindowFrame
	// contains filtered or unexported fields
}

PhysicalWindow is the physical operator of window function.

func (*PhysicalWindow) Attach2Task

func (p *PhysicalWindow) Attach2Task(tasks ...base.Task) base.Task

Attach2Task implements the PhysicalPlan interface.

func (*PhysicalWindow) Clone

func (p *PhysicalWindow) Clone(newCtx base.PlanContext) (base.PhysicalPlan, error)

Clone implements op.PhysicalPlan interface.

func (*PhysicalWindow) ExplainInfo

func (p *PhysicalWindow) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PhysicalWindow) ExtractCorrelatedCols

func (p *PhysicalWindow) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements op.PhysicalPlan interface.

func (PhysicalWindow) Init

Init initializes PhysicalWindow.

func (*PhysicalWindow) MemoryUsage

func (p *PhysicalWindow) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PhysicalWindow

func (*PhysicalWindow) ResolveIndices

func (p *PhysicalWindow) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*PhysicalWindow) Schema

func (s *PhysicalWindow) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PhysicalWindow) SetSchema

func (s *PhysicalWindow) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

func (*PhysicalWindow) ToPB

func (p *PhysicalWindow) ToPB(ctx *base.BuildPBContext, storeType kv.StoreType) (*tipb.Executor, error)

ToPB implements PhysicalPlan ToPB interface.

type PlanBuilder

type PlanBuilder struct {
	// contains filtered or unexported fields
}

PlanBuilder builds Plan from an ast.Node. It just builds the ast node straightforwardly.

func NewPlanBuilder

func NewPlanBuilder(opts ...PlanBuilderOpt) *PlanBuilder

NewPlanBuilder creates a new PlanBuilder.

func (*PlanBuilder) Build

func (b *PlanBuilder) Build(ctx context.Context, node *resolve.NodeW) (base.Plan, error)

Build builds the ast node to a Plan.

func (*PlanBuilder) BuildDataSourceFromView

func (b *PlanBuilder) BuildDataSourceFromView(ctx context.Context, dbName pmodel.CIStr, tableInfo *model.TableInfo, qbNameMap4View map[string][]ast.HintTable, viewHints map[string][]*ast.TableOptimizerHint) (base.LogicalPlan, error)

BuildDataSourceFromView is used to build base.LogicalPlan from view qbNameMap4View and viewHints are used for the view's hint. qbNameMap4View maps the query block name to the view table lists. viewHints group the view hints based on the view's query block name.

func (*PlanBuilder) GetIsForUpdateRead

func (b *PlanBuilder) GetIsForUpdateRead() bool

GetIsForUpdateRead gets if the PlanBuilder use forUpdateRead

func (*PlanBuilder) GetOptFlag

func (b *PlanBuilder) GetOptFlag() uint64

GetOptFlag gets the OptFlag of the PlanBuilder.

func (*PlanBuilder) GetVisitInfo

func (b *PlanBuilder) GetVisitInfo() []visitInfo

GetVisitInfo gets the visitInfo of the PlanBuilder.

func (*PlanBuilder) Init

Init initialize a PlanBuilder. Return the original PlannerSelectBlockAsName as well, callers decide if PlannerSelectBlockAsName should be restored after using this builder. This is The comman code pattern to use it: NewPlanBuilder().Init(sctx, is, processor)

func (*PlanBuilder) ResetForReuse

func (b *PlanBuilder) ResetForReuse() *PlanBuilder

ResetForReuse reset the plan builder, put it into pool for reuse. After reset for reuse, the object should be equal to a object returned by NewPlanBuilder().

func (*PlanBuilder) TableHints

func (b *PlanBuilder) TableHints() *h.PlanHints

TableHints returns the *TableHintInfo of PlanBuilder.

type PlanBuilderOpt

type PlanBuilderOpt interface {
	Apply(builder *PlanBuilder)
}

PlanBuilderOpt is used to adjust the plan builder.

type PlanBuilderOptAllowCastArray

type PlanBuilderOptAllowCastArray struct{}

PlanBuilderOptAllowCastArray means the plan builder should allow build cast(... as ... array).

func (PlanBuilderOptAllowCastArray) Apply

func (PlanBuilderOptAllowCastArray) Apply(builder *PlanBuilder)

Apply implements the interface PlanBuilderOpt.

type PlanBuilderOptNoExecution

type PlanBuilderOptNoExecution struct{}

PlanBuilderOptNoExecution means the plan builder should not run any executor during Build().

func (PlanBuilderOptNoExecution) Apply

func (PlanBuilderOptNoExecution) Apply(builder *PlanBuilder)

Apply implements the interface PlanBuilderOpt.

type PlanCacheKeyEnableInstancePlanCache

type PlanCacheKeyEnableInstancePlanCache struct{}

PlanCacheKeyEnableInstancePlanCache is only for test.

type PlanCacheKeyTestClone

type PlanCacheKeyTestClone struct{}

PlanCacheKeyTestClone is only for test.

type PlanCacheKeyTestIssue43667

type PlanCacheKeyTestIssue43667 struct{}

PlanCacheKeyTestIssue43667 is only for test.

type PlanCacheKeyTestIssue46760

type PlanCacheKeyTestIssue46760 struct{}

PlanCacheKeyTestIssue46760 is only for test.

type PlanCacheKeyTestIssue47133

type PlanCacheKeyTestIssue47133 struct{}

PlanCacheKeyTestIssue47133 is only for test.

type PlanCacheStmt

type PlanCacheStmt struct {
	PreparedAst *ast.Prepared
	ResolveCtx  *resolve.Context
	StmtDB      string // which DB the statement will be processed over
	VisitInfos  []visitInfo
	Params      []ast.ParamMarkerExpr

	PointGet PointGetExecutorCache

	// below fields are for PointGet short path
	SchemaVersion int64

	// RelateVersion stores the true cache plan table schema version, since each table schema can be updated separately in transaction.
	RelateVersion map[int64]uint64

	StmtCacheable     bool   // Whether this stmt is cacheable.
	UncacheableReason string // Why this stmt is uncacheable.

	NormalizedSQL       string
	NormalizedPlan      string
	SQLDigest           *parser.Digest
	PlanDigest          *parser.Digest
	ForUpdateRead       bool
	SnapshotTSEvaluator func(context.Context, sessionctx.Context) (uint64, error)

	BindingInfo bindinfo.BindingMatchInfo

	// the different between NormalizedSQL, NormalizedSQL4PC and StmtText:
	//  for the query `select * from t where a>1 and b<?`, then
	//  NormalizedSQL: select * from `t` where `a` > ? and `b` < ? --> constants are normalized to '?',
	//  NormalizedSQL4PC: select * from `test` . `t` where `a` > ? and `b` < ? --> schema name is added,
	//  StmtText: select * from t where a>1 and b <? --> just format the original query;
	StmtText string
	// contains filtered or unexported fields
}

PlanCacheStmt store prepared ast from PrepareExec and other related fields

func GeneratePlanCacheStmtWithAST

func GeneratePlanCacheStmtWithAST(ctx context.Context, sctx sessionctx.Context, isPrepStmt bool,
	paramSQL string, paramStmt ast.StmtNode, is infoschema.InfoSchema) (*PlanCacheStmt, base.Plan, int, error)

GeneratePlanCacheStmtWithAST generates the PlanCacheStmt structure for this AST. paramSQL is the corresponding parameterized sql like 'select * from t where a<? and b>?'. paramStmt is the Node of paramSQL.

func GetPreparedStmt

func GetPreparedStmt(stmt *ast.ExecuteStmt, vars *variable.SessionVars) (*PlanCacheStmt, error)

GetPreparedStmt extract the prepared statement from the execute statement.

type PlanCacheValue

type PlanCacheValue struct {
	// Meta Info, all are READ-ONLY once initialized.
	SQLDigest        string
	SQLText          string
	StmtType         string             // select, update, insert, delete, etc.
	ParseUser        string             // the user who parses/compiles this plan.
	Binding          string             // the binding of this plan.
	OptimizerEnvHash string             // other environment information that might affect the plan like "time_zone", "sql_mode".
	ParseValues      string             // the actual values used when parsing/compiling this plan.
	PlanDigest       string             // digest of the plan, used to identify the plan in the cache.
	BinaryPlan       string             // binary of this Plan, use tidb_decode_binary_plan to decode this.
	Memory           int64              // the memory usage of this plan, in bytes.
	LoadTime         time.Time          // the time when this plan is loaded into the cache.
	Plan             base.Plan          // READ-ONLY for Instance Cache, READ-WRITE for Session Cache.
	OutputColumns    types.NameSlice    // output column names of this plan
	ParamTypes       []*types.FieldType // all parameters' types, different parameters may share same plan
	StmtHints        *hint.StmtHints    // related hints of this plan, like 'max_execution_time'.
	// contains filtered or unexported fields
}

PlanCacheValue stores the cached Statement and StmtNode.

func NewPlanCacheValue

func NewPlanCacheValue(
	sctx sessionctx.Context,
	stmt *PlanCacheStmt,
	cacheKey string,
	binding string,
	plan base.Plan,
	names []*types.FieldName,
	paramTypes []*types.FieldType,
	stmtHints *hint.StmtHints,
) *PlanCacheValue

NewPlanCacheValue creates a SQLCacheValue.

func (*PlanCacheValue) MemoryUsage

func (v *PlanCacheValue) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PlanCacheValue

func (*PlanCacheValue) RuntimeInfo

func (v *PlanCacheValue) RuntimeInfo() (exec, procKeys, totKeys, sumLat int64, lastUsedTime time.Time)

RuntimeInfo returns the runtime information of the plan.

func (*PlanCacheValue) UpdateRuntimeInfo

func (v *PlanCacheValue) UpdateRuntimeInfo(proKeys, totKeys, latency int64)

UpdateRuntimeInfo accumulates the runtime information of the plan.

type PlanReplayer

type PlanReplayer struct {
	ExecStmt          ast.StmtNode
	Analyze           bool
	Load              bool
	File              string
	HistoricalStatsTS uint64

	Capture    bool
	Remove     bool
	SQLDigest  string
	PlanDigest string
	// contains filtered or unexported fields
}

PlanReplayer represents a plan replayer plan.

func (*PlanReplayer) MemoryUsage

func (s *PlanReplayer) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*PlanReplayer) OutputNames

func (s *PlanReplayer) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*PlanReplayer) ResolveIndices

func (*PlanReplayer) ResolveIndices() (err error)

func (*PlanReplayer) Schema

func (s *PlanReplayer) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*PlanReplayer) SetOutputNames

func (s *PlanReplayer) SetOutputNames(names types.NameSlice)

func (*PlanReplayer) SetSchema

func (s *PlanReplayer) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PointGetExecutorCache

type PointGetExecutorCache struct {
	ColumnInfos any
	// Executor is only used for point get scene.
	// Notice that we should only cache the PointGetExecutor that have a snapshot with MaxTS in it.
	// If the current plan is not PointGet or does not use MaxTS optimization, this value should be nil here.
	Executor any

	// FastPlan is only used for instance plan cache.
	// To ensure thread-safe, we have to clone each plan before reusing if using instance plan cache.
	// To reduce the memory allocation and increase performance, we cache the FastPlan here.
	FastPlan *PointGetPlan
}

PointGetExecutorCache caches the PointGetExecutor to further improve its performance. Don't forget to reset this executor when the prior plan is invalid.

type PointGetPlan

type PointGetPlan struct {
	baseimpl.Plan

	// explicit partition selection
	PartitionNames []pmodel.CIStr `plan-cache-clone:"shallow"`

	TblInfo        *model.TableInfo `plan-cache-clone:"shallow"`
	IndexInfo      *model.IndexInfo `plan-cache-clone:"shallow"`
	PartitionIdx   *int
	Handle         kv.Handle
	HandleConstant *expression.Constant

	HandleColOffset  int
	IndexValues      []types.Datum
	IndexConstants   []*expression.Constant
	ColsFieldType    []*types.FieldType `plan-cache-clone:"shallow"`
	IdxCols          []*expression.Column
	IdxColLens       []int
	AccessConditions []expression.Expression
	UnsignedHandle   bool
	IsTableDual      bool
	Lock             bool

	LockWaitTime int64
	Columns      []*model.ColumnInfo `plan-cache-clone:"shallow"`
	// contains filtered or unexported fields
}

PointGetPlan is a fast plan for simple point get. When we detect that the statement has a unique equal access condition, this plan is used. This plan is much faster to build and to execute because it avoids the optimization and coprocessor cost.

func FastClonePointGetForPlanCache

func FastClonePointGetForPlanCache(newCtx base.PlanContext, src, dst *PointGetPlan) *PointGetPlan

FastClonePointGetForPlanCache is a fast path to clone a PointGetPlan for plan cache.

func (*PointGetPlan) AccessObject

func (p *PointGetPlan) AccessObject() base.AccessObject

AccessObject implements dataAccesser interface.

func (*PointGetPlan) AppendChildCandidate

func (*PointGetPlan) AppendChildCandidate(_ *optimizetrace.PhysicalOptimizeOp)

AppendChildCandidate implements PhysicalPlan interface.

func (*PointGetPlan) Attach2Task

func (*PointGetPlan) Attach2Task(...base.Task) base.Task

Attach2Task makes the current physical plan as the father of task's physicalPlan and updates the cost of current task. If the child's task is cop task, some operator may close this task and return a new rootTask.

func (*PointGetPlan) Children

func (*PointGetPlan) Children() []base.PhysicalPlan

Children gets all the children.

func (*PointGetPlan) Clone

Clone implements PhysicalPlan interface.

func (*PointGetPlan) CloneForPlanCache

func (op *PointGetPlan) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (*PointGetPlan) Cost

func (p *PointGetPlan) Cost() float64

Cost implements PhysicalPlan interface

func (*PointGetPlan) ExplainInfo

func (p *PointGetPlan) ExplainInfo() string

ExplainInfo implements Plan interface.

func (*PointGetPlan) ExplainNormalizedInfo

func (p *PointGetPlan) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements Plan interface.

func (*PointGetPlan) ExtractCorrelatedCols

func (*PointGetPlan) ExtractCorrelatedCols() []*expression.CorrelatedColumn

ExtractCorrelatedCols implements PhysicalPlan interface.

func (*PointGetPlan) GetActualProbeCnt

func (p *PointGetPlan) GetActualProbeCnt(statsColl *execdetails.RuntimeStatsColl) int64

GetActualProbeCnt implements PhysicalPlan interface.

func (*PointGetPlan) GetAvgRowSize

func (p *PointGetPlan) GetAvgRowSize() float64

GetAvgRowSize return the average row size.

func (*PointGetPlan) GetChildReqProps

func (*PointGetPlan) GetChildReqProps(_ int) *property.PhysicalProperty

GetChildReqProps gets the required property by child index.

func (*PointGetPlan) GetCost

GetCost returns cost of the PointGetPlan.

func (*PointGetPlan) GetEstRowCountForDisplay

func (p *PointGetPlan) GetEstRowCountForDisplay() float64

GetEstRowCountForDisplay implements PhysicalPlan interface.

func (*PointGetPlan) GetPlanCostVer1

func (p *PointGetPlan) GetPlanCostVer1(_ property.TaskType, option *optimizetrace.PlanCostOption) (float64, error)

GetPlanCostVer1 calculates the cost of the plan if it has not been calculated yet and returns the cost.

func (*PointGetPlan) GetPlanCostVer2

func (p *PointGetPlan) GetPlanCostVer2(taskType property.TaskType, option *optimizetrace.PlanCostOption) (costusage.CostVer2, error)

GetPlanCostVer2 returns the plan-cost of this sub-plan, which is:

func (PointGetPlan) Init

Init initializes PointGetPlan.

func (*PointGetPlan) LoadTableStats

func (p *PointGetPlan) LoadTableStats(ctx sessionctx.Context)

LoadTableStats preloads the stats data for the physical table

func (*PointGetPlan) MemoryUsage

func (p *PointGetPlan) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PointGetPlan

func (*PointGetPlan) OperatorInfo

func (p *PointGetPlan) OperatorInfo(normalized bool) string

OperatorInfo implements dataAccesser interface.

func (*PointGetPlan) OutputNames

func (p *PointGetPlan) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*PointGetPlan) PrunePartitions

func (p *PointGetPlan) PrunePartitions(sctx sessionctx.Context) bool

PrunePartitions will check which partition to use returns true if no matching partition

func (*PointGetPlan) ResolveIndices

func (p *PointGetPlan) ResolveIndices() error

ResolveIndices resolves the indices for columns. After doing this, the columns can evaluate the rows by their indices.

func (*PointGetPlan) Schema

func (p *PointGetPlan) Schema() *expression.Schema

Schema implements the Plan interface.

func (*PointGetPlan) SetChild

func (*PointGetPlan) SetChild(_ int, _ base.PhysicalPlan)

SetChild sets a specific child for the plan.

func (*PointGetPlan) SetChildren

func (*PointGetPlan) SetChildren(...base.PhysicalPlan)

SetChildren sets the children for the plan.

func (*PointGetPlan) SetCost

func (p *PointGetPlan) SetCost(cost float64)

SetCost implements PhysicalPlan interface

func (*PointGetPlan) SetOutputNames

func (p *PointGetPlan) SetOutputNames(names types.NameSlice)

SetOutputNames sets the outputting name by the given slice.

func (*PointGetPlan) SetProbeParents

func (p *PointGetPlan) SetProbeParents(probeParents []base.PhysicalPlan)

SetProbeParents implements PhysicalPlan interface.

func (*PointGetPlan) StatsCount

func (*PointGetPlan) StatsCount() float64

StatsCount will return the RowCount of property.StatsInfo for this plan.

func (*PointGetPlan) StatsInfo

func (p *PointGetPlan) StatsInfo() *property.StatsInfo

StatsInfo will return the RowCount of property.StatsInfo for this plan.

func (*PointGetPlan) ToPB

func (*PointGetPlan) ToPB(_ *base.BuildPBContext, _ kv.StoreType) (*tipb.Executor, error)

ToPB converts physical plan to tipb executor.

type PointPlanVal

type PointPlanVal struct {
	Plan base.Plan
}

PointPlanVal is used to store point plan that is pre-built for multi-statement query. Save the plan in a struct so even if the point plan is nil, we don't need to try again.

type PredicateSimplification

type PredicateSimplification struct {
}

PredicateSimplification consolidates different predcicates on a column and its equivalence classes. Initial out is for

  1. in-list and not equal list intersection.
  2. Drop OR predicates if they are empty for this pattern: P AND (P1 OR P2 ... OR Pn) Pi is removed if P & Pi is false/empty.
  3. Simplify predicates with logical constants (True/False).

func (*PredicateSimplification) Name

Name implements base.LogicalOptRule.<1st> interface.

func (*PredicateSimplification) Optimize

Optimize implements base.LogicalOptRule.<0th> interface.

type Prepare

type Prepare struct {
	Name    string
	SQLText string
	// contains filtered or unexported fields
}

Prepare represents prepare plan.

func (*Prepare) MemoryUsage

func (s *Prepare) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*Prepare) OutputNames

func (s *Prepare) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Prepare) ResolveIndices

func (*Prepare) ResolveIndices() (err error)

func (*Prepare) Schema

func (s *Prepare) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Prepare) SetOutputNames

func (s *Prepare) SetOutputNames(names types.NameSlice)

func (*Prepare) SetSchema

func (s *Prepare) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type PreprocessOpt

type PreprocessOpt func(*preprocessor)

PreprocessOpt presents optional parameters to `Preprocess` method.

func WithPreprocessorReturn

func WithPreprocessorReturn(ret *PreprocessorReturn) PreprocessOpt

WithPreprocessorReturn returns a PreprocessOpt to initialize the PreprocessorReturn.

type PreprocessorReturn

type PreprocessorReturn struct {
	IsStaleness         bool
	SnapshotTSEvaluator func(context.Context, sessionctx.Context) (uint64, error)
	// LastSnapshotTS is the last evaluated snapshotTS if any
	// otherwise it defaults to zero
	LastSnapshotTS uint64
	InfoSchema     infoschema.InfoSchema
	// contains filtered or unexported fields
}

PreprocessorReturn is used to retain information obtained in the preprocessor.

type ProjectionEliminator

type ProjectionEliminator struct {
}

ProjectionEliminator is for update stmt The projection eliminate in logical optimize has been forbidden. The projection eliminate in post optimize will optimize the projection under the projection, window, agg (the condition is same as logical optimize)

func (*ProjectionEliminator) Name

func (*ProjectionEliminator) Name() string

Name implements the logicalOptRule.<1st> interface.

func (*ProjectionEliminator) Optimize

Optimize implements the logicalOptRule interface.

type PushDownSequenceSolver

type PushDownSequenceSolver struct {
}

PushDownSequenceSolver is used to push down sequence.

func (*PushDownSequenceSolver) Name

Name implements the base.LogicalOptRule.<1st> interface.

func (*PushDownSequenceSolver) Optimize

Optimize implements the base.LogicalOptRule.<0th> interface.

type PushDownTopNOptimizer

type PushDownTopNOptimizer struct {
}

PushDownTopNOptimizer pushes down the topN or limit. In the future we will remove the limit from `requiredProperty` in CBO phase.

func (*PushDownTopNOptimizer) Name

func (*PushDownTopNOptimizer) Name() string

Name implements the base.LogicalOptRule.<1st> interface.

func (*PushDownTopNOptimizer) Optimize

Optimize implements the base.LogicalOptRule.<0th> interface.

type PushedDownLimit

type PushedDownLimit struct {
	Offset uint64
	Count  uint64
}

PushedDownLimit is the limit operator pushed down into PhysicalIndexLookUpReader.

func (*PushedDownLimit) Clone

func (p *PushedDownLimit) Clone() *PushedDownLimit

Clone clones this pushed-down list.

func (*PushedDownLimit) MemoryUsage

func (p *PushedDownLimit) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of PushedDownLimit

type ReadReqType

type ReadReqType uint8

ReadReqType is the read request type of the operator. Currently, only PhysicalTableReader uses this.

const (
	// Cop means read from storage by cop request.
	Cop ReadReqType = iota
	// BatchCop means read from storage by BatchCop request, only used for TiFlash
	BatchCop
	// MPP means read from storage by MPP request, only used for TiFlash
	MPP
)

func (ReadReqType) Name

func (r ReadReqType) Name() string

Name returns the name of read request type.

type RecommendIndexPlan

type RecommendIndexPlan struct {
	Action   string
	SQL      string
	AdviseID int64
	Options  []ast.RecommendIndexOption
	// contains filtered or unexported fields
}

RecommendIndexPlan represents a plan for recommend index stmt.

func (*RecommendIndexPlan) MemoryUsage

func (s *RecommendIndexPlan) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*RecommendIndexPlan) OutputNames

func (s *RecommendIndexPlan) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*RecommendIndexPlan) ResolveIndices

func (*RecommendIndexPlan) ResolveIndices() (err error)

func (*RecommendIndexPlan) Schema

func (s *RecommendIndexPlan) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*RecommendIndexPlan) SetOutputNames

func (s *RecommendIndexPlan) SetOutputNames(names types.NameSlice)

func (*RecommendIndexPlan) SetSchema

func (s *RecommendIndexPlan) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type RecoverIndex

type RecoverIndex struct {
	Table     *resolve.TableNameW
	IndexName string
	// contains filtered or unexported fields
}

RecoverIndex is used for backfilling corrupted index data.

func (*RecoverIndex) MemoryUsage

func (s *RecoverIndex) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*RecoverIndex) OutputNames

func (s *RecoverIndex) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*RecoverIndex) ResolveIndices

func (*RecoverIndex) ResolveIndices() (err error)

func (*RecoverIndex) Schema

func (s *RecoverIndex) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*RecoverIndex) SetOutputNames

func (s *RecoverIndex) SetOutputNames(names types.NameSlice)

func (*RecoverIndex) SetSchema

func (s *RecoverIndex) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ReloadExprPushdownBlacklist

type ReloadExprPushdownBlacklist struct {
	// contains filtered or unexported fields
}

ReloadExprPushdownBlacklist reloads the data from expr_pushdown_blacklist table.

func (*ReloadExprPushdownBlacklist) MemoryUsage

func (s *ReloadExprPushdownBlacklist) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*ReloadExprPushdownBlacklist) OutputNames

func (s *ReloadExprPushdownBlacklist) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*ReloadExprPushdownBlacklist) ResolveIndices

func (*ReloadExprPushdownBlacklist) ResolveIndices() (err error)

func (*ReloadExprPushdownBlacklist) Schema

func (s *ReloadExprPushdownBlacklist) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*ReloadExprPushdownBlacklist) SetOutputNames

func (s *ReloadExprPushdownBlacklist) SetOutputNames(names types.NameSlice)

func (*ReloadExprPushdownBlacklist) SetSchema

func (s *ReloadExprPushdownBlacklist) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ReloadOptRuleBlacklist

type ReloadOptRuleBlacklist struct {
	// contains filtered or unexported fields
}

ReloadOptRuleBlacklist reloads the data from opt_rule_blacklist table.

func (*ReloadOptRuleBlacklist) MemoryUsage

func (s *ReloadOptRuleBlacklist) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*ReloadOptRuleBlacklist) OutputNames

func (s *ReloadOptRuleBlacklist) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*ReloadOptRuleBlacklist) ResolveIndices

func (*ReloadOptRuleBlacklist) ResolveIndices() (err error)

func (*ReloadOptRuleBlacklist) Schema

func (s *ReloadOptRuleBlacklist) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*ReloadOptRuleBlacklist) SetOutputNames

func (s *ReloadOptRuleBlacklist) SetOutputNames(names types.NameSlice)

func (*ReloadOptRuleBlacklist) SetSchema

func (s *ReloadOptRuleBlacklist) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ResolveExpand

type ResolveExpand struct {
}

ResolveExpand generating Expand projection list when all the logical optimization is done.

func (*ResolveExpand) Name

func (*ResolveExpand) Name() string

Name implements the base.LogicalOptRule.<1st> interface.

func (*ResolveExpand) Optimize

Optimize implements the base.LogicalOptRule.<0th> interface. By now, rollup syntax will build a LogicalExpand from bottom up. In LogicalExpand itself, its schema out should be 3 parts:

+---------------------------------------------------------------------+

child.output() + grouping sets column + genCol(gid, gpos)

+---------------------------------------------------------------------+

select count(a) from t group by a, b+1, c with rollup

Aggregation: (group by a, col#1, c, gid); aggFunc: count(a)
    |
    +------> Expand: schema[a, a', col#1, c, gid]; L1-projection[a, a', col#1, c, 0],   L2-projection[a, a', col#1, null, 1]
               |                                  L3-projection[a, a', null, null, 2], L3-projection[a, null, null, null, 3]
               |
               +-------> Projection:   a,        a',      b+1 as column#1,      c
                                       |         +------------------------------+
                              (upper required)   (grouping sets columns appended)

Expand operator itself is kind like a projection, while difference is that it has a multi projection list, named as leveled projection.

type ResultReorder

type ResultReorder struct {
}

ResultReorder reorder query results. NOTE: it's not a common rule for all queries, it's specially implemented for a few customers.

Results of some queries are not ordered, for example:

create table t (a int); insert into t values (1), (2); select a from t;

In the case above, the result can be `1 2` or `2 1`, which is not ordered. This rule reorders results by modifying or injecting a Sort operator:

  1. iterate the plan from the root, and ignore all input-order operators (Sel/Proj/Limit);
  2. when meeting the first non-input-order operator, 2.1. if it's a Sort, update it by appending all output columns into its order-by list, 2.2. otherwise, inject a new Sort upon this operator.

func (*ResultReorder) Name

func (*ResultReorder) Name() string

Name implements base.LogicalOptRule.<1st> interface.

func (*ResultReorder) Optimize

Optimize implements base.LogicalOptRule.<0th> interface.

type ResumeDDLJobs

type ResumeDDLJobs struct {
	JobIDs []int64
	// contains filtered or unexported fields
}

ResumeDDLJobs indicates a plan to resume the Paused DDL Jobs.

func (*ResumeDDLJobs) MemoryUsage

func (s *ResumeDDLJobs) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*ResumeDDLJobs) OutputNames

func (s *ResumeDDLJobs) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*ResumeDDLJobs) ResolveIndices

func (*ResumeDDLJobs) ResolveIndices() (err error)

func (*ResumeDDLJobs) Schema

func (s *ResumeDDLJobs) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*ResumeDDLJobs) SetOutputNames

func (s *ResumeDDLJobs) SetOutputNames(names types.NameSlice)

func (*ResumeDDLJobs) SetSchema

func (s *ResumeDDLJobs) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type RootTask

type RootTask struct {
	// contains filtered or unexported fields
}

RootTask is the final sink node of a plan graph. It should be a single goroutine on tidb.

func (*RootTask) ConvertToRootTask

func (t *RootTask) ConvertToRootTask(_ base.PlanContext) base.Task

ConvertToRootTask implements Task interface.

func (*RootTask) Copy

func (t *RootTask) Copy() base.Task

Copy implements Task interface.

func (*RootTask) Count

func (t *RootTask) Count() float64

Count implements Task interface.

func (*RootTask) GetPlan

func (t *RootTask) GetPlan() base.PhysicalPlan

GetPlan returns the root task's plan.

func (*RootTask) Invalid

func (t *RootTask) Invalid() bool

Invalid implements Task interface.

func (*RootTask) IsEmpty

func (t *RootTask) IsEmpty() bool

IsEmpty indicates whether root task is empty.

func (*RootTask) MemoryUsage

func (t *RootTask) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of rootTask

func (*RootTask) Plan

func (t *RootTask) Plan() base.PhysicalPlan

Plan implements Task interface.

func (*RootTask) SetEmpty

func (t *RootTask) SetEmpty(x bool)

SetEmpty set the root task as empty.

func (*RootTask) SetPlan

func (t *RootTask) SetPlan(p base.PhysicalPlan)

SetPlan sets the root task' plan.

type RuntimeFilter

type RuntimeFilter struct {
	// contains filtered or unexported fields
}

RuntimeFilter structure is generated by the Runtime Filter Generator. At present, it has a one-to-one correspondence with the equivalent expression in HashJoin. For example: Query: select * from t1, t2 where t1.k1=t2.k1 PhysicalPlanTree:

HashJoin_2(t1.k2=t2.k1)
/           \

TableScan_0(t1) ExchangeNode_1 RuntimeFilter struct:

id: 0
buildNode: HashJoin
srcExprList: [t2.k1]
targetExprList: [t1.k1]
rfType:  IN
rfMode: LOCAL
buildNodeID: 2
targetNodeID: 0

Although srcExprList and targetExprList attributes are lists, in fact, there will only be one value in them at present. The reason why it is designed as a list is because: Reserve an interface for subsequent multiple join equivalent expressions corresponding to one rf. (Since IN supports multiple columns, this construction can be more efficient at the execution level)

func NewRuntimeFilter

func NewRuntimeFilter(rfIDGenerator *util.IDGenerator, eqPredicate *expression.ScalarFunction, buildNode *PhysicalHashJoin) ([]*RuntimeFilter, int64)

NewRuntimeFilter construct runtime filter by Join and equal predicate of Join

func (*RuntimeFilter) Clone

func (rf *RuntimeFilter) Clone() *RuntimeFilter

Clone deep copy of runtime filter

func (*RuntimeFilter) ExplainInfo

func (rf *RuntimeFilter) ExplainInfo(isBuildNode bool) string

ExplainInfo explain info of runtime filter

func (*RuntimeFilter) String

func (rf *RuntimeFilter) String() string

func (*RuntimeFilter) ToPB

func (rf *RuntimeFilter) ToPB(ctx *base.BuildPBContext, client kv.Client) (*tipb.RuntimeFilter, error)

ToPB convert runtime filter to PB

type RuntimeFilterGenerator

type RuntimeFilterGenerator struct {
	// contains filtered or unexported fields
}

RuntimeFilterGenerator One plan one generator

func (*RuntimeFilterGenerator) GenerateRuntimeFilter

func (generator *RuntimeFilterGenerator) GenerateRuntimeFilter(plan base.PhysicalPlan)

GenerateRuntimeFilter is the root method. It traverses the entire tree in preorder. It constructs RF when encountering hash join, and allocate RF when encountering table scan. It realizes the planning of RF in the entire plan tree. For example:

PhysicalPlanTree:

     HashJoin
      /     \
TableScan   ExchangeNode
  1. generateRuntimeFilter HashJoin (with RF1) / \ TableScan ExchangeNode
  1. assignRuntimeFilter HashJoin (with RF1) / \ TableScan ExchangeNode

(assign RF1)

type RuntimeFilterMode

type RuntimeFilterMode = variable.RuntimeFilterMode

RuntimeFilterMode "OFF", "LOCAL"

type RuntimeFilterType

type RuntimeFilterType = variable.RuntimeFilterType

RuntimeFilterType "IN"

type SQLBindOpDetail

type SQLBindOpDetail struct {
	NormdOrigSQL string
	BindSQL      string
	BindStmt     ast.StmtNode
	Db           string
	Charset      string
	Collation    string
	NewStatus    string
	Source       string // Source indicate how this binding was created, eg: bindinfo.Manual or bindinfo.History
	SQLDigest    string
	PlanDigest   string
}

SQLBindOpDetail represents the detail of an operation on a single binding. Different SQLBindOpType use different fields in this struct.

type SQLBindOpType

type SQLBindOpType int

SQLBindOpType repreents the SQL bind type

const (
	// OpSQLBindCreate represents the operation to create a SQL bind.
	OpSQLBindCreate SQLBindOpType = iota
	// OpSQLBindDrop represents the operation to drop a SQL bind.
	OpSQLBindDrop
	// OpFlushBindings is used to flush plan bindings.
	OpFlushBindings
	// OpCaptureBindings is used to capture plan bindings.
	OpCaptureBindings
	// OpReloadBindings is used to reload plan binding.
	OpReloadBindings
	// OpSetBindingStatus is used to set binding status.
	OpSetBindingStatus
	// OpSQLBindDropByDigest is used to drop SQL binds by digest
	OpSQLBindDropByDigest
	// OpSetBindingStatusByDigest represents the operation to set SQL binding status by sql digest.
	OpSetBindingStatusByDigest
)

type SQLBindPlan

type SQLBindPlan struct {
	IsGlobal  bool
	SQLBindOp SQLBindOpType
	Details   []*SQLBindOpDetail
	// contains filtered or unexported fields
}

SQLBindPlan represents a plan for SQL bind. One SQLBindPlan can be either global or session, and can only contain one type of operation, but can contain multiple operations of that type.

func (*SQLBindPlan) MemoryUsage

func (s *SQLBindPlan) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*SQLBindPlan) OutputNames

func (s *SQLBindPlan) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*SQLBindPlan) ResolveIndices

func (*SQLBindPlan) ResolveIndices() (err error)

func (*SQLBindPlan) Schema

func (s *SQLBindPlan) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*SQLBindPlan) SetOutputNames

func (s *SQLBindPlan) SetOutputNames(names types.NameSlice)

func (*SQLBindPlan) SetSchema

func (s *SQLBindPlan) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ScalarSubQueryExpr

type ScalarSubQueryExpr struct {
	expression.Constant
	// contains filtered or unexported fields
}

ScalarSubQueryExpr is a expression placeholder for the non-correlated scalar subqueries which can be evaluated during optimizing phase. TODO: The methods related with evaluate the function will be revised in next step.

func (*ScalarSubQueryExpr) CanonicalHashCode

func (s *ScalarSubQueryExpr) CanonicalHashCode() []byte

CanonicalHashCode implements the Expression interface.

func (*ScalarSubQueryExpr) Clone

Clone copies an expression totally.

func (*ScalarSubQueryExpr) ConstLevel

ConstLevel returns the const level for the expression

func (*ScalarSubQueryExpr) Decorrelate

Decorrelate implements the Expression interface.

func (*ScalarSubQueryExpr) Equal

Equal implements the Expression interface.

func (*ScalarSubQueryExpr) Equals

func (s *ScalarSubQueryExpr) Equals(other any) bool

Equals implements the HashEquals.<1st> interface.

func (*ScalarSubQueryExpr) Eval

Eval implements the Expression interface.

func (*ScalarSubQueryExpr) EvalDecimal

func (*ScalarSubQueryExpr) EvalDecimal(_ expression.EvalContext, _ chunk.Row) (val *types.MyDecimal, isNull bool, err error)

EvalDecimal returns the decimal representation of expression.

func (*ScalarSubQueryExpr) EvalDuration

func (*ScalarSubQueryExpr) EvalDuration(_ expression.EvalContext, _ chunk.Row) (val types.Duration, isNull bool, err error)

EvalDuration returns the duration representation of expression.

func (*ScalarSubQueryExpr) EvalInt

func (*ScalarSubQueryExpr) EvalInt(_ expression.EvalContext, _ chunk.Row) (val int64, isNull bool, err error)

EvalInt returns the int64 representation of expression.

func (*ScalarSubQueryExpr) EvalJSON

func (*ScalarSubQueryExpr) EvalJSON(_ expression.EvalContext, _ chunk.Row) (val types.BinaryJSON, isNull bool, err error)

EvalJSON returns the JSON representation of expression.

func (*ScalarSubQueryExpr) EvalReal

func (*ScalarSubQueryExpr) EvalReal(_ expression.EvalContext, _ chunk.Row) (val float64, isNull bool, err error)

EvalReal returns the float64 representation of expression.

func (*ScalarSubQueryExpr) EvalString

func (*ScalarSubQueryExpr) EvalString(_ expression.EvalContext, _ chunk.Row) (val string, isNull bool, err error)

EvalString returns the string representation of expression.

func (*ScalarSubQueryExpr) EvalTime

func (*ScalarSubQueryExpr) EvalTime(_ expression.EvalContext, _ chunk.Row) (val types.Time, isNull bool, err error)

EvalTime returns the DATE/DATETIME/TIMESTAMP representation of expression.

func (*ScalarSubQueryExpr) ExplainInfo

ExplainInfo implements the Expression interface.

func (*ScalarSubQueryExpr) ExplainNormalizedInfo

func (s *ScalarSubQueryExpr) ExplainNormalizedInfo() string

ExplainNormalizedInfo implements the Expression interface.

func (*ScalarSubQueryExpr) GetType

GetType implements the Expression interface.

func (*ScalarSubQueryExpr) Hash64

func (s *ScalarSubQueryExpr) Hash64(h base2.Hasher)

Hash64 implements the HashEquals.<0th> interface.

func (*ScalarSubQueryExpr) HashCode

func (s *ScalarSubQueryExpr) HashCode() []byte

HashCode implements the Expression interface.

func (*ScalarSubQueryExpr) IsCorrelated

func (*ScalarSubQueryExpr) IsCorrelated() bool

IsCorrelated implements the Expression interface.

func (*ScalarSubQueryExpr) MemoryUsage

func (s *ScalarSubQueryExpr) MemoryUsage() int64

MemoryUsage implements the Expression interface.

func (*ScalarSubQueryExpr) RemapColumn

RemapColumn implements the Expression interface.

func (*ScalarSubQueryExpr) ResolveIndices

ResolveIndices implements the Expression interface.

func (*ScalarSubQueryExpr) ResolveIndicesByVirtualExpr

func (s *ScalarSubQueryExpr) ResolveIndicesByVirtualExpr(_ expression.EvalContext, _ *expression.Schema) (expression.Expression, bool)

ResolveIndicesByVirtualExpr implements the Expression interface.

func (*ScalarSubQueryExpr) String

func (s *ScalarSubQueryExpr) String() string

String implements the Stringer interface.

func (*ScalarSubQueryExpr) Traverse

Traverse implements the TraverseDown interface.

func (*ScalarSubQueryExpr) VecEvalDecimal

VecEvalDecimal evaluates this expression in a vectorized manner.

func (*ScalarSubQueryExpr) VecEvalDuration

func (*ScalarSubQueryExpr) VecEvalDuration(_ expression.EvalContext, _ *chunk.Chunk, _ *chunk.Column) error

VecEvalDuration evaluates this expression in a vectorized manner.

func (*ScalarSubQueryExpr) VecEvalInt

VecEvalInt evaluates this expression in a vectorized manner.

func (*ScalarSubQueryExpr) VecEvalJSON

VecEvalJSON evaluates this expression in a vectorized manner.

func (*ScalarSubQueryExpr) VecEvalReal

VecEvalReal evaluates this expression in a vectorized manner.

func (*ScalarSubQueryExpr) VecEvalString

VecEvalString evaluates this expression in a vectorized manner.

func (*ScalarSubQueryExpr) VecEvalTime

VecEvalTime evaluates this expression in a vectorized manner.

func (*ScalarSubQueryExpr) Vectorized

func (*ScalarSubQueryExpr) Vectorized() bool

Vectorized returns whether the expression can be vectorized.

type ScalarSubqueryEvalCtx

type ScalarSubqueryEvalCtx struct {
	baseimpl.Plan
	// contains filtered or unexported fields
}

ScalarSubqueryEvalCtx store the plan for the subquery, used by ScalarSubQueryExpr.

func (*ScalarSubqueryEvalCtx) ExplainInfo

func (ssctx *ScalarSubqueryEvalCtx) ExplainInfo() string

ExplainInfo implements the Plan interface.

func (ScalarSubqueryEvalCtx) Init

Init initializes ScalarSubqueryEvalCtx

func (*ScalarSubqueryEvalCtx) Schema

Schema implements the Plan interface.

type ScanAccessObject

type ScanAccessObject struct {
	Database   string
	Table      string
	Indexes    []IndexAccess
	Partitions []string
}

ScanAccessObject represents the access to a table. It may also represent the access to indexes and partitions of a table.

func (*ScanAccessObject) NormalizedString

func (s *ScanAccessObject) NormalizedString() string

NormalizedString implements AccessObject.

func (*ScanAccessObject) SetIntoPB

func (s *ScanAccessObject) SetIntoPB(pb *tipb.ExplainOperator)

SetIntoPB implements AccessObject.

func (*ScanAccessObject) String

func (s *ScanAccessObject) String() string

type SelectInto

type SelectInto struct {
	TargetPlan base.Plan
	IntoOpt    *ast.SelectIntoOption
	LineFieldsInfo
	// contains filtered or unexported fields
}

SelectInto represents a select-into plan.

func (*SelectInto) MemoryUsage

func (s *SelectInto) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*SelectInto) OutputNames

func (s *SelectInto) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*SelectInto) ResolveIndices

func (*SelectInto) ResolveIndices() (err error)

func (*SelectInto) Schema

func (s *SelectInto) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*SelectInto) SetOutputNames

func (s *SelectInto) SetOutputNames(names types.NameSlice)

func (*SelectInto) SetSchema

func (s *SelectInto) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type SemiJoinRewriter

type SemiJoinRewriter struct {
}

SemiJoinRewriter rewrites semi join to inner join with aggregation. Note: This rewriter is only used for exists subquery. And it also requires the hint `SEMI_JOIN_REWRITE` to be set. For example:

select * from t where exists (select /*+ SEMI_JOIN_REWRITE() */ * from s where s.a = t.a);

will be rewriten to:

select * from t join (select a from s group by a) s on t.a = s.a;

func (*SemiJoinRewriter) Name

func (*SemiJoinRewriter) Name() string

Name implements base.LogicalOptRule.<1st> interface.

func (*SemiJoinRewriter) Optimize

Optimize implements base.LogicalOptRule.<0th> interface.

type Set

type Set struct {
	VarAssigns []*expression.VarAssignment
	// contains filtered or unexported fields
}

Set represents a plan for set stmt.

func (*Set) MemoryUsage

func (s *Set) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*Set) OutputNames

func (s *Set) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Set) ResolveIndices

func (*Set) ResolveIndices() (err error)

func (*Set) Schema

func (s *Set) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Set) SetOutputNames

func (s *Set) SetOutputNames(names types.NameSlice)

func (*Set) SetSchema

func (s *Set) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type SetConfig

type SetConfig struct {
	Type     string
	Instance string
	Name     string
	Value    expression.Expression
	// contains filtered or unexported fields
}

SetConfig represents a plan for set config stmt.

func (*SetConfig) MemoryUsage

func (s *SetConfig) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*SetConfig) OutputNames

func (s *SetConfig) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*SetConfig) ResolveIndices

func (*SetConfig) ResolveIndices() (err error)

func (*SetConfig) Schema

func (s *SetConfig) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*SetConfig) SetOutputNames

func (s *SetConfig) SetOutputNames(names types.NameSlice)

func (*SetConfig) SetSchema

func (s *SetConfig) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ShowBaseExtractor

type ShowBaseExtractor struct {
	ast.ShowStmt
	// contains filtered or unexported fields
}

ShowBaseExtractor is the definition of base extractor for derived predicates.

func (*ShowBaseExtractor) ExplainInfo

func (e *ShowBaseExtractor) ExplainInfo() string

ExplainInfo implements the base.ShowPredicateExtractor interface.

func (*ShowBaseExtractor) Extract

func (e *ShowBaseExtractor) Extract() bool

Extract implements the ShowPredicateExtractor interface.

func (*ShowBaseExtractor) Field

func (e *ShowBaseExtractor) Field() string

Field will return the variable `field` in ShowBaseExtractor

func (*ShowBaseExtractor) FieldPatternLike

func (e *ShowBaseExtractor) FieldPatternLike() collate.WildcardPattern

FieldPatternLike will return compiled collate.WildcardPattern

type ShowDDL

type ShowDDL struct {
	// contains filtered or unexported fields
}

ShowDDL is for showing DDL information.

func (*ShowDDL) MemoryUsage

func (s *ShowDDL) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*ShowDDL) OutputNames

func (s *ShowDDL) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*ShowDDL) ResolveIndices

func (*ShowDDL) ResolveIndices() (err error)

func (*ShowDDL) Schema

func (s *ShowDDL) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*ShowDDL) SetOutputNames

func (s *ShowDDL) SetOutputNames(names types.NameSlice)

func (*ShowDDL) SetSchema

func (s *ShowDDL) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ShowDDLJobQueries

type ShowDDLJobQueries struct {
	JobIDs []int64
	// contains filtered or unexported fields
}

ShowDDLJobQueries is for showing DDL job queries sql.

func (*ShowDDLJobQueries) MemoryUsage

func (s *ShowDDLJobQueries) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*ShowDDLJobQueries) OutputNames

func (s *ShowDDLJobQueries) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*ShowDDLJobQueries) ResolveIndices

func (*ShowDDLJobQueries) ResolveIndices() (err error)

func (*ShowDDLJobQueries) Schema

func (s *ShowDDLJobQueries) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*ShowDDLJobQueries) SetOutputNames

func (s *ShowDDLJobQueries) SetOutputNames(names types.NameSlice)

func (*ShowDDLJobQueries) SetSchema

func (s *ShowDDLJobQueries) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ShowDDLJobQueriesWithRange

type ShowDDLJobQueriesWithRange struct {
	Limit  uint64
	Offset uint64
	// contains filtered or unexported fields
}

ShowDDLJobQueriesWithRange is for showing DDL job queries sql with specified limit and offset.

func (*ShowDDLJobQueriesWithRange) MemoryUsage

func (s *ShowDDLJobQueriesWithRange) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*ShowDDLJobQueriesWithRange) OutputNames

func (s *ShowDDLJobQueriesWithRange) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*ShowDDLJobQueriesWithRange) ResolveIndices

func (*ShowDDLJobQueriesWithRange) ResolveIndices() (err error)

func (*ShowDDLJobQueriesWithRange) Schema

func (s *ShowDDLJobQueriesWithRange) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*ShowDDLJobQueriesWithRange) SetOutputNames

func (s *ShowDDLJobQueriesWithRange) SetOutputNames(names types.NameSlice)

func (*ShowDDLJobQueriesWithRange) SetSchema

func (s *ShowDDLJobQueriesWithRange) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ShowNextRowID

type ShowNextRowID struct {
	TableName *ast.TableName
	// contains filtered or unexported fields
}

ShowNextRowID is for showing the next global row ID.

func (*ShowNextRowID) MemoryUsage

func (s *ShowNextRowID) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*ShowNextRowID) OutputNames

func (s *ShowNextRowID) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*ShowNextRowID) ResolveIndices

func (*ShowNextRowID) ResolveIndices() (err error)

func (*ShowNextRowID) Schema

func (s *ShowNextRowID) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*ShowNextRowID) SetOutputNames

func (s *ShowNextRowID) SetOutputNames(names types.NameSlice)

func (*ShowNextRowID) SetSchema

func (s *ShowNextRowID) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type ShowSlow

type ShowSlow struct {
	*ast.ShowSlow
	// contains filtered or unexported fields
}

ShowSlow is for showing slow queries.

func (*ShowSlow) MemoryUsage

func (s *ShowSlow) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*ShowSlow) OutputNames

func (s *ShowSlow) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*ShowSlow) ResolveIndices

func (*ShowSlow) ResolveIndices() (err error)

func (*ShowSlow) Schema

func (s *ShowSlow) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*ShowSlow) SetOutputNames

func (s *ShowSlow) SetOutputNames(names types.NameSlice)

func (*ShowSlow) SetSchema

func (s *ShowSlow) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type Simple

type Simple struct {
	Statement ast.StmtNode

	// IsFromRemote indicates whether the statement IS FROM REMOTE TiDB instance in cluster,
	//   and executing in co-processor.
	//   Used for `global kill`. See https://github.com/pingcap/tidb/blob/master/docs/design/2020-06-01-global-kill.md.
	IsFromRemote bool

	// StaleTxnStartTS is the StartTS that is used to build a staleness transaction by 'START TRANSACTION READ ONLY' statement.
	StaleTxnStartTS uint64

	ResolveCtx *resolve.Context
	// contains filtered or unexported fields
}

Simple represents a simple statement plan which doesn't need any optimization.

func (*Simple) MemoryUsage

func (s *Simple) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of Simple

func (*Simple) OutputNames

func (s *Simple) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Simple) ResolveIndices

func (*Simple) ResolveIndices() (err error)

func (*Simple) Schema

func (s *Simple) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Simple) SetOutputNames

func (s *Simple) SetOutputNames(names types.NameSlice)

func (*Simple) SetSchema

func (s *Simple) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type SkewDistinctAggRewriter

type SkewDistinctAggRewriter struct {
}

SkewDistinctAggRewriter rewrites group distinct aggregate into 2 level aggregates.

func (*SkewDistinctAggRewriter) Name

Name implements base.LogicalOptRule.<1st> interface.

func (*SkewDistinctAggRewriter) Optimize

Optimize implements base.LogicalOptRule.<0th> interface.

type SlowQueryExtractor

type SlowQueryExtractor struct {
	SkipRequest bool
	TimeRanges  []*TimeRange
	// Enable is true means the executor should use the time range to locate the slow-log file that need to be parsed.
	// Enable is false, means the executor should keep the behavior compatible with before, which is only parse the
	// current slow-log file.
	Enable bool
	Desc   bool
	// contains filtered or unexported fields
}

SlowQueryExtractor is used to extract some predicates of `slow_query`

func (*SlowQueryExtractor) ExplainInfo

func (e *SlowQueryExtractor) ExplainInfo(pp base.PhysicalPlan) string

ExplainInfo implements the base.MemTablePredicateExtractor interface.

func (*SlowQueryExtractor) Extract

func (e *SlowQueryExtractor) Extract(ctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) []expression.Expression

Extract implements the MemTablePredicateExtractor Extract interface

type SplitRegion

type SplitRegion struct {
	TableInfo      *model.TableInfo
	PartitionNames []pmodel.CIStr
	IndexInfo      *model.IndexInfo
	Lower          []types.Datum
	Upper          []types.Datum
	Num            int
	ValueLists     [][]types.Datum
	// contains filtered or unexported fields
}

SplitRegion represents a split regions plan.

func (*SplitRegion) MemoryUsage

func (s *SplitRegion) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*SplitRegion) OutputNames

func (s *SplitRegion) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*SplitRegion) ResolveIndices

func (*SplitRegion) ResolveIndices() (err error)

func (*SplitRegion) Schema

func (s *SplitRegion) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*SplitRegion) SetOutputNames

func (s *SplitRegion) SetOutputNames(names types.NameSlice)

func (*SplitRegion) SetSchema

func (s *SplitRegion) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type SplitRegionStatus

type SplitRegionStatus struct {
	Table     table.Table
	IndexInfo *model.IndexInfo
	// contains filtered or unexported fields
}

SplitRegionStatus represents a split regions status plan.

func (*SplitRegionStatus) MemoryUsage

func (s *SplitRegionStatus) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*SplitRegionStatus) OutputNames

func (s *SplitRegionStatus) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*SplitRegionStatus) ResolveIndices

func (*SplitRegionStatus) ResolveIndices() (err error)

func (*SplitRegionStatus) Schema

func (s *SplitRegionStatus) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*SplitRegionStatus) SetOutputNames

func (s *SplitRegionStatus) SetOutputNames(names types.NameSlice)

func (*SplitRegionStatus) SetSchema

func (s *SplitRegionStatus) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type StatementsSummaryExtractor

type StatementsSummaryExtractor struct {

	// SkipRequest means the where clause always false, we don't need to request any component
	SkipRequest bool
	// Digests represents digest applied to, and we should apply all digest if there is no digest specified.
	// e.g: SELECT * FROM STATEMENTS_SUMMARY WHERE digest='8019af26debae8aa7642c501dbc43212417b3fb14e6aec779f709976b7e521be'
	Digests set.StringSet

	// Coarse time range predicate extracted from the where clause as:
	// SELECT ... WHERE summary_begin_time <= endTime AND summary_end_time >= startTime
	//
	// N.B. it's only used by v2, so we should keep predicates not changed when extracting time range, or it will
	// affect the correctness with v1.
	CoarseTimeRange *TimeRange
	// contains filtered or unexported fields
}

StatementsSummaryExtractor is used to extract some predicates of statements summary table.

func (*StatementsSummaryExtractor) ExplainInfo

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*StatementsSummaryExtractor) Extract

func (e *StatementsSummaryExtractor) Extract(sctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) (remained []expression.Expression)

Extract implements the MemTablePredicateExtractor Extract interface

type SyncWaitStatsLoadPoint

type SyncWaitStatsLoadPoint struct{}

SyncWaitStatsLoadPoint sync-wait for stats load point.

func (SyncWaitStatsLoadPoint) Name

Name implements the base.LogicalOptRule.<1st> interface.

func (SyncWaitStatsLoadPoint) Optimize

Optimize implements the base.LogicalOptRule.<0th> interface.

type TableStorageStatsExtractor

type TableStorageStatsExtractor struct {

	// SkipRequest means the where clause always false, we don't need to request any component.
	SkipRequest bool
	// TableSchema represents tableSchema applied to, and we should apply all table disk usage if there is no schema specified.
	// e.g: SELECT * FROM information_schema.disk_usage WHERE table_schema in ('test', 'information_schema').
	TableSchema set.StringSet
	// TableName represents tableName applied to, and we should apply all table disk usage if there is no table specified.
	// e.g: SELECT * FROM information_schema.disk_usage WHERE table in ('schemata', 'tables').
	TableName set.StringSet
	// contains filtered or unexported fields
}

TableStorageStatsExtractor is used to extract some predicates of `disk_usage`.

func (*TableStorageStatsExtractor) ExplainInfo

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*TableStorageStatsExtractor) Extract

Extract implements the MemTablePredicateExtractor Extract interface.

type TblColPosInfo

type TblColPosInfo struct {
	TblID int64
	// Start and End represent the ordinal range [Start, End) of the consecutive columns.
	Start, End int
	// HandleOrdinal represents the ordinal of the handle column.
	HandleCols util.HandleCols

	*table.ExtraPartialRowOption
}

TblColPosInfo represents an mapper from column index to handle index.

func (*TblColPosInfo) MemoryUsage

func (t *TblColPosInfo) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of TblColPosInfo

type TblColPosInfoSlice

type TblColPosInfoSlice []TblColPosInfo

TblColPosInfoSlice attaches the methods of sort.Interface to []TblColPosInfos sorting in increasing order.

func (TblColPosInfoSlice) FindTblIdx

func (c TblColPosInfoSlice) FindTblIdx(colOrdinal int) (int, bool)

FindTblIdx finds the ordinal of the corresponding access column.

func (TblColPosInfoSlice) Len

func (c TblColPosInfoSlice) Len() int

Len implements sort.Interface#Len.

func (TblColPosInfoSlice) Less

func (c TblColPosInfoSlice) Less(i, j int) bool

Less implements sort.Interface#Less.

func (TblColPosInfoSlice) Swap

func (c TblColPosInfoSlice) Swap(i, j int)

Swap implements sort.Interface#Swap.

type TiFlashSystemTableExtractor

type TiFlashSystemTableExtractor struct {

	// SkipRequest means the where clause always false, we don't need to request any component
	SkipRequest bool
	// TiFlashInstances represents all tiflash instances we should send request to.
	// e.g:
	// 1. SELECT * FROM information_schema.<table_name> WHERE tiflash_instance='192.168.1.7:3930'
	// 2. SELECT * FROM information_schema.<table_name> WHERE tiflash_instance in ('192.168.1.7:3930', '192.168.1.9:3930')
	TiFlashInstances set.StringSet
	// TidbDatabases represents tidbDatabases applied to, and we should apply all tidb database if there is no database specified.
	// e.g: SELECT * FROM information_schema.<table_name> WHERE tidb_database in ('test', 'test2').
	TiDBDatabases string
	// TidbTables represents tidbTables applied to, and we should apply all tidb table if there is no table specified.
	// e.g: SELECT * FROM information_schema.<table_name> WHERE tidb_table in ('t', 't2').
	TiDBTables string
	// contains filtered or unexported fields
}

TiFlashSystemTableExtractor is used to extract some predicates of tiflash system table.

func (*TiFlashSystemTableExtractor) ExplainInfo

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*TiFlashSystemTableExtractor) Extract

Extract implements the MemTablePredicateExtractor Extract interface

type TiKVRegionStatusExtractor

type TiKVRegionStatusExtractor struct {
	// contains filtered or unexported fields
}

TiKVRegionStatusExtractor is used to extract single table region scan region from predictions

func (*TiKVRegionStatusExtractor) ExplainInfo

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*TiKVRegionStatusExtractor) Extract

func (e *TiKVRegionStatusExtractor) Extract(ctx base.PlanContext,
	schema *expression.Schema,
	names []*types.FieldName,
	predicates []expression.Expression,
) (remained []expression.Expression)

Extract implements the MemTablePredicateExtractor Extract interface

func (*TiKVRegionStatusExtractor) GetTablesID

func (e *TiKVRegionStatusExtractor) GetTablesID() []int64

GetTablesID returns TablesID

type TikvRegionPeersExtractor

type TikvRegionPeersExtractor struct {

	// SkipRequest means the where clause always false, we don't need to request any component
	SkipRequest bool

	// RegionIDs/StoreIDs represents all region/store ids we should filter in PD to reduce network IO.
	// e.g:
	// 1. SELECT * FROM tikv_region_peers WHERE region_id=1
	// 2. SELECT * FROM tikv_region_peers WHERE table_id in (11, 22)
	RegionIDs []uint64
	StoreIDs  []uint64
	// contains filtered or unexported fields
}

TikvRegionPeersExtractor is used to extract some predicates of cluster table.

func (*TikvRegionPeersExtractor) ExplainInfo

ExplainInfo implements base.MemTablePredicateExtractor interface.

func (*TikvRegionPeersExtractor) Extract

Extract implements the MemTablePredicateExtractor Extract interface

type TimeRange

type TimeRange struct {
	StartTime time.Time
	EndTime   time.Time
}

TimeRange is used to check whether a given log should be extracted.

type Trace

type Trace struct {
	StmtNode   ast.StmtNode
	ResolveCtx *resolve.Context
	Format     string

	// OptimizerTrace indicates `trace plan target = 'xxx' <statement>` case
	OptimizerTrace       bool
	OptimizerTraceTarget string
	// contains filtered or unexported fields
}

Trace represents a trace plan.

func (*Trace) MemoryUsage

func (s *Trace) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*Trace) OutputNames

func (s *Trace) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Trace) ResolveIndices

func (*Trace) ResolveIndices() (err error)

func (*Trace) Schema

func (s *Trace) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Trace) SetOutputNames

func (s *Trace) SetOutputNames(names types.NameSlice)

func (*Trace) SetSchema

func (s *Trace) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type Traffic

type Traffic struct {
	OpType  ast.TrafficOpType
	Options []*ast.TrafficOption
	Dir     string
	// contains filtered or unexported fields
}

Traffic represents a traffic plan.

func (*Traffic) MemoryUsage

func (s *Traffic) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*Traffic) OutputNames

func (s *Traffic) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Traffic) ResolveIndices

func (*Traffic) ResolveIndices() (err error)

func (*Traffic) Schema

func (s *Traffic) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Traffic) SetOutputNames

func (s *Traffic) SetOutputNames(names types.NameSlice)

func (*Traffic) SetSchema

func (s *Traffic) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type UnlockStats

type UnlockStats struct {
	Tables []*ast.TableName
	// contains filtered or unexported fields
}

UnlockStats represents a unlock stats for table

func (*UnlockStats) MemoryUsage

func (s *UnlockStats) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of baseSchemaProducer

func (*UnlockStats) OutputNames

func (s *UnlockStats) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*UnlockStats) ResolveIndices

func (*UnlockStats) ResolveIndices() (err error)

func (*UnlockStats) Schema

func (s *UnlockStats) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*UnlockStats) SetOutputNames

func (s *UnlockStats) SetOutputNames(names types.NameSlice)

func (*UnlockStats) SetSchema

func (s *UnlockStats) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type Update

type Update struct {
	OrderedList []*expression.Assignment

	AllAssignmentsAreConstant bool

	IgnoreError bool

	VirtualAssignmentsOffset int

	SelectPlan base.PhysicalPlan

	// TblColPosInfos is for multi-table update statement.
	// It records the column position of each related table.
	TblColPosInfos TblColPosInfoSlice `plan-cache-clone:"shallow"`

	// Used when partition sets are given.
	// e.g. update t partition(p0) set a = 1;
	PartitionedTable []table.PartitionedTable `plan-cache-clone:"shallow"`

	FKChecks   map[int64][]*FKCheck   `plan-cache-clone:"must-nil"`
	FKCascades map[int64][]*FKCascade `plan-cache-clone:"must-nil"`
	// contains filtered or unexported fields
}

Update represents Update plan.

func (*Update) CloneForPlanCache

func (op *Update) CloneForPlanCache(newCtx base.PlanContext) (base.Plan, bool)

CloneForPlanCache implements the base.Plan interface.

func (Update) Init

func (p Update) Init(ctx base.PlanContext) *Update

Init initializes Update.

func (*Update) MemoryUsage

func (p *Update) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of Update

func (*Update) OutputNames

func (s *Update) OutputNames() types.NameSlice

OutputNames returns the outputting names of each column.

func (*Update) ResolveIndices

func (p *Update) ResolveIndices() (err error)

ResolveIndices implements Plan interface.

func (*Update) Schema

func (s *Update) Schema() *expression.Schema

Schema implements the Plan.Schema interface.

func (*Update) SetOutputNames

func (s *Update) SetOutputNames(names types.NameSlice)

func (*Update) SetSchema

func (s *Update) SetSchema(schema *expression.Schema)

SetSchema implements the Plan.SetSchema interface.

type V2AnalyzeOptions

type V2AnalyzeOptions struct {
	PhyTableID  int64
	RawOpts     map[ast.AnalyzeOptionType]uint64
	FilledOpts  map[ast.AnalyzeOptionType]uint64
	ColChoice   pmodel.ColumnChoice
	ColumnList  []*model.ColumnInfo
	IsPartition bool
}

V2AnalyzeOptions is used to hold analyze options information.

type VectorIndexExtra

type VectorIndexExtra struct {
	// Note: Even if IndexInfo is not nil, it doesn't mean the VectorSearch push down
	// will happen because optimizer will explore all available vector indexes and fill them
	// in IndexInfo, and later invalid plans are filtered out according to a topper executor.
	IndexInfo *model.IndexInfo

	// Not nil if there is an VectorSearch push down.
	PushDownQueryInfo *tipb.ANNQueryInfo
}

VectorIndexExtra is the extra information for vector index.

type WindowFuncExtractor

type WindowFuncExtractor struct {
	// contains filtered or unexported fields
}

WindowFuncExtractor visits Expr tree. It converts ColumnNameExpr to WindowFuncExpr and collects WindowFuncExpr.

func (*WindowFuncExtractor) Enter

func (*WindowFuncExtractor) Enter(n ast.Node) (ast.Node, bool)

Enter implements Visitor interface.

func (*WindowFuncExtractor) Leave

func (a *WindowFuncExtractor) Leave(n ast.Node) (ast.Node, bool)

Leave implements Visitor interface.

Source Files

Directories

Path Synopsis
generator
operator
Package resolve is used for semantic resolve of the AST tree.
Package resolve is used for semantic resolve of the AST tree.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL