stmtctx

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: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ReferenceCountIsFrozen indicates the current StmtCtx is resetting, it'll refuse all the access from other sessions.
	ReferenceCountIsFrozen int32 = -1
	// ReferenceCountNoReference indicates the current StmtCtx is not accessed by other sessions.
	ReferenceCountNoReference int32 = 0
)

Variables

View Source
var DefaultStmtErrLevels = func() (l errctx.LevelMap) {
	l[errctx.ErrGroupDividedByZero] = errctx.LevelWarn
	return
}()

DefaultStmtErrLevels is the default error levels for statement

Functions

func AllocateTaskID

func AllocateTaskID() uint64

AllocateTaskID allocates a new unique ID for a statement execution

func PushDownFlagsWithTypeFlagsAndErrLevels

func PushDownFlagsWithTypeFlagsAndErrLevels(tcFlags types.Flags, errLevels errctx.LevelMap) uint64

PushDownFlagsWithTypeFlagsAndErrLevels applies gets the related bits to push down flags with `type.Flags` and `errctx.LevelMap`

Types

type PlanCacheType

type PlanCacheType int

PlanCacheType is the flag of plan cache

const (
	// DefaultNoCache no cache
	DefaultNoCache PlanCacheType = iota
	// SessionPrepared session prepared plan cache
	SessionPrepared
	// SessionNonPrepared session non-prepared plan cache
	SessionNonPrepared
)

type ReferenceCount

type ReferenceCount int32

ReferenceCount indicates the reference count of StmtCtx.

func (*ReferenceCount) Decrease

func (rf *ReferenceCount) Decrease()

Decrease decreases the reference count.

func (*ReferenceCount) TryFreeze

func (rf *ReferenceCount) TryFreeze() bool

TryFreeze tries to freeze the StmtCtx to frozen before resetting the old StmtCtx.

func (*ReferenceCount) TryIncrease

func (rf *ReferenceCount) TryIncrease() bool

TryIncrease tries to increase the reference count. There is a small chance that TryIncrease returns true while TryFreeze and UnFreeze are invoked successfully during the execution of TryIncrease.

func (*ReferenceCount) UnFreeze

func (rf *ReferenceCount) UnFreeze()

UnFreeze unfreeze the frozen StmtCtx thus the other session can access this StmtCtx.

type ReservedRowIDAlloc

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

ReservedRowIDAlloc is used to reserve autoID for the auto_increment column.

func (*ReservedRowIDAlloc) Consume

func (r *ReservedRowIDAlloc) Consume() (int64, bool)

Consume consumes a reserved rowID. If the second return value is false, it means the reserved rowID is exhausted.

func (*ReservedRowIDAlloc) Exhausted

func (r *ReservedRowIDAlloc) Exhausted() bool

Exhausted returns whether the reserved rowID is exhausted.

func (*ReservedRowIDAlloc) Reset

func (r *ReservedRowIDAlloc) Reset(base int64, maxv int64)

Reset resets the base and max of reserved rowIDs.

type SQLWarn

type SQLWarn = contextutil.SQLWarn

SQLWarn relates a sql warning and it's level.

type StatementContext

type StatementContext struct {

	// Set the following variables before execution
	hint.StmtHints

	// IsDDLJobInQueue is used to mark whether the DDL job is put into the queue.
	// If IsDDLJobInQueue is true, it means the DDL job is in the queue of storage, and it can be handled by the DDL worker.
	IsDDLJobInQueue        bool
	DDLJobID               int64
	InInsertStmt           bool
	InUpdateStmt           bool
	InDeleteStmt           bool
	InSelectStmt           bool
	InLoadDataStmt         bool
	InExplainStmt          bool
	InExplainAnalyzeStmt   bool
	ExplainFormat          string
	InCreateOrAlterStmt    bool
	InSetSessionStatesStmt bool
	InPreparedPlanBuilding bool
	InShowWarning          bool

	contextutil.PlanCacheTracker
	contextutil.RangeFallbackHandler

	IgnoreExplainIDSuffix bool
	MultiSchemaInfo       *model.MultiSchemaInfo
	// If the select statement was like 'select * from t as of timestamp ...' or in a stale read transaction
	// or is affected by the tidb_read_staleness session variable, then the statement will be makred as isStaleness
	// in stmtCtx
	IsStaleness     bool
	InRestrictedSQL bool
	ViewDepth       int32

	WarnHandler contextutil.WarnHandlerExt
	// ExtraWarnHandler record the extra warnings and are only used by the slow log only now.
	// If a warning is expected to be output only under some conditions (like in EXPLAIN or EXPLAIN VERBOSE) but it's
	// not under such conditions now, it is considered as an extra warning.
	// extraWarnings would not be printed through SHOW WARNINGS, but we want to always output them through the slow
	// log to help diagnostics, so we store them here separately.
	ExtraWarnHandler contextutil.WarnHandlerExt

	execdetails.SyncExecDetails

	// PrevAffectedRows is the affected-rows value(DDL is 0, DML is the number of affected rows).
	PrevAffectedRows int64
	// PrevLastInsertID is the last insert ID of previous statement.
	PrevLastInsertID uint64
	// LastInsertID is the auto-generated ID in the current statement.
	LastInsertID uint64
	// InsertID is the given insert ID of an auto_increment column.
	InsertID uint64

	// ReservedRowIDAlloc is used to alloc auto ID from the reserved IDs.
	ReservedRowIDAlloc ReservedRowIDAlloc

	// Copied from SessionVars.TimeZone.
	Priority     mysql.PriorityEnum
	NotFillCache bool
	MemTracker   *memory.Tracker
	DiskTracker  *disk.Tracker
	// per statement resource group name
	// hint /* +ResourceGroup(name) */ can change the statement group name
	ResourceGroupName   string
	RunawayChecker      resourcegroup.RunawayChecker
	IsTiFlash           atomic2.Bool
	RuntimeStatsColl    *execdetails.RuntimeStatsColl
	IndexUsageCollector *indexusage.StmtIndexUsageCollector
	TableIDs            []int64
	IndexNames          []string
	StmtType            string
	OriginalSQL         string

	// BindSQL used to construct the key for plan cache. It records the binding used by the stmt.
	// If the binding is not used by the stmt, the value is empty
	BindSQL string

	Tables []TableEntry

	PessimisticLockWaited int32
	LockKeysDuration      int64
	LockKeysCount         int32
	LockTableIDs          map[int64]struct{} // table IDs need to be locked, empty for lock all tables
	TblInfo2UnionScan     map[*model.TableInfo]bool
	TaskID                uint64 // unique ID for an execution of a statement
	TaskMapBakTS          uint64 // counter for

	// Map to store all CTE storages of current SQL.
	// Will clean up at the end of the execution.
	CTEStorageMap any

	SetVarHintRestore map[string]string

	// If the statement read from table cache, this flag is set.
	ReadFromTableCache bool

	// InVerboseExplain indicates the statement is "explain format='verbose' ...".
	InVerboseExplain bool

	// EnableOptimizeTrace indicates whether enable optimizer trace by 'trace plan statement'
	EnableOptimizeTrace bool
	// OptimizeTracer indicates the tracer for optimize
	OptimizeTracer *tracing.OptimizeTracer

	// EnableOptimizerCETrace indicate if cardinality estimation internal process needs to be traced.
	// CE Trace is currently a submodule of the optimizer trace and is controlled by a separated option.
	EnableOptimizerCETrace bool
	OptimizerCETrace       []*tracing.CETraceRecord

	EnableOptimizerDebugTrace bool
	OptimizerDebugTrace       any

	// WaitLockLeaseTime is the duration of cached table read lease expiration time.
	WaitLockLeaseTime time.Duration

	// KvExecCounter is created from SessionVars.StmtStats to count the number of SQL
	// executions of the kv layer during the current execution of the statement.
	// Its life cycle is limited to this execution, and a new KvExecCounter is
	// always created during each statement execution.
	KvExecCounter *stmtstats.KvExecCounter

	// WeakConsistency is true when read consistency is weak and in a read statement and not in a transaction.
	WeakConsistency bool

	StatsLoad struct {
		// Timeout to wait for sync-load
		Timeout time.Duration
		// NeededItems stores the columns/indices whose stats are needed for planner.
		NeededItems []model.StatsLoadItem
		// ResultCh to receive stats loading results
		ResultCh []<-chan singleflight.Result
		// LoadStartTime is to record the load start time to calculate latency
		LoadStartTime time.Time
	}

	// SysdateIsNow indicates whether sysdate() is an alias of now() in this statement
	SysdateIsNow bool

	// RCCheckTS indicates the current read-consistency read select statement will use `RCCheckTS` path.
	RCCheckTS bool

	// IsSQLRegistered uses to indicate whether the SQL has been registered for TopSQL.
	IsSQLRegistered atomic2.Bool
	// IsSQLAndPlanRegistered uses to indicate whether the SQL and plan has been registered for TopSQL.
	IsSQLAndPlanRegistered atomic2.Bool
	// IsReadOnly uses to indicate whether the SQL is read-only.
	IsReadOnly bool

	// IsSyncStatsFailed indicates whether any failure happened during sync stats
	IsSyncStatsFailed bool
	// UseDynamicPruneMode indicates whether use UseDynamicPruneMode in query stmt
	UseDynamicPruneMode bool
	// ColRefFromPlan mark the column ref used by assignment in update statement.
	ColRefFromUpdatePlan intset.FastIntSet

	// IsExplainAnalyzeDML is true if the statement is "explain analyze DML executors", before responding the explain
	// results to the client, the transaction should be committed first. See issue #37373 for more details.
	IsExplainAnalyzeDML bool

	// InHandleForeignKeyTrigger indicates currently are handling foreign key trigger.
	InHandleForeignKeyTrigger bool

	// ForeignKeyTriggerCtx is the contain information for foreign key cascade execution.
	ForeignKeyTriggerCtx struct {
		// The SavepointName is use to do rollback when handle foreign key cascade failed.
		SavepointName string
		HasFKCascades bool
	}

	// MPPQueryInfo stores some id and timestamp of current MPP query statement.
	MPPQueryInfo struct {
		QueryID              atomic2.Uint64
		QueryTS              atomic2.Uint64
		AllocatedMPPTaskID   atomic2.Int64
		AllocatedMPPGatherID atomic2.Uint64
	}

	// TableStats stores the visited runtime table stats by table id during query
	TableStats map[int64]any

	// Check if TiFlash read engine is removed due to strict sql mode.
	TiFlashEngineRemovedDueToStrictSQLMode bool
	// StaleTSOProvider is used to provide stale timestamp oracle for read-only transactions.
	StaleTSOProvider struct {
		sync.Mutex
		// contains filtered or unexported fields
	}

	// MDLRelatedTableIDs is used to store the table IDs that are related to the current MDL lock.
	MDLRelatedTableIDs map[int64]struct{}

	// ForShareLockEnabledByNoop indicates whether the current statement contains `for share` clause
	// and the `for share` execution is enabled by `tidb_enable_noop_functions`, no locks should be
	// acquired in this case.
	ForShareLockEnabledByNoop bool
	// contains filtered or unexported fields
}

StatementContext contains variables for a statement. It should be reset before executing a statement.

func NewStmtCtx

func NewStmtCtx() *StatementContext

NewStmtCtx creates a new statement context

func NewStmtCtxWithTimeZone

func NewStmtCtxWithTimeZone(tz *time.Location) *StatementContext

NewStmtCtxWithTimeZone creates a new StatementContext with the given timezone

func (*StatementContext) AddAffectedRows

func (sc *StatementContext) AddAffectedRows(rows uint64)

AddAffectedRows adds affected rows.

func (*StatementContext) AddCopiedRows

func (sc *StatementContext) AddCopiedRows(rows uint64)

AddCopiedRows adds copied rows.

func (*StatementContext) AddDeletedRows

func (sc *StatementContext) AddDeletedRows(rows uint64)

AddDeletedRows adds record rows.

func (*StatementContext) AddFoundRows

func (sc *StatementContext) AddFoundRows(rows uint64)

AddFoundRows adds found rows.

func (*StatementContext) AddRecordRows

func (sc *StatementContext) AddRecordRows(rows uint64)

AddRecordRows adds record rows.

func (*StatementContext) AddSetVarHintRestore

func (sc *StatementContext) AddSetVarHintRestore(name, val string)

AddSetVarHintRestore records the variables which are affected by SET_VAR hint. And restore them to the old value later.

func (*StatementContext) AddTouchedRows

func (sc *StatementContext) AddTouchedRows(rows uint64)

AddTouchedRows adds touched rows.

func (*StatementContext) AddUpdatedRows

func (sc *StatementContext) AddUpdatedRows(rows uint64)

AddUpdatedRows adds updated rows.

func (*StatementContext) AffectedRows

func (sc *StatementContext) AffectedRows() uint64

AffectedRows gets affected rows.

func (*StatementContext) AppendError

func (sc *StatementContext) AppendError(warn error)

AppendError appends a warning with level 'Error'.

func (*StatementContext) AppendExtraError

func (sc *StatementContext) AppendExtraError(warn error)

AppendExtraError appends an extra warning with level 'Error'.

func (*StatementContext) AppendExtraNote

func (sc *StatementContext) AppendExtraNote(warn error)

AppendExtraNote appends an extra warning with level 'Note'.

func (*StatementContext) AppendExtraWarning

func (sc *StatementContext) AppendExtraWarning(warn error)

AppendExtraWarning appends an extra warning with level 'Warning'.

func (*StatementContext) AppendNote

func (sc *StatementContext) AppendNote(warn error)

AppendNote appends a warning with level 'Note'.

func (*StatementContext) AppendWarning

func (sc *StatementContext) AppendWarning(warn error)

AppendWarning appends a warning with level 'Warning'.

func (*StatementContext) AppendWarnings

func (sc *StatementContext) AppendWarnings(warns []SQLWarn)

AppendWarnings appends some warnings.

func (*StatementContext) ClearUseChunkAlloc

func (sc *StatementContext) ClearUseChunkAlloc()

ClearUseChunkAlloc clear useChunkAlloc status

func (*StatementContext) CopiedRows

func (sc *StatementContext) CopiedRows() uint64

CopiedRows is used to generate info message

func (*StatementContext) CopyWarnings

func (sc *StatementContext) CopyWarnings(dst []SQLWarn) []SQLWarn

CopyWarnings copies the warnings to the dst.

func (*StatementContext) CtxID

func (sc *StatementContext) CtxID() uint64

CtxID returns the context id of the statement

func (*StatementContext) DeletedRows

func (sc *StatementContext) DeletedRows() uint64

DeletedRows is used to generate info message

func (*StatementContext) DetachMemDiskTracker

func (sc *StatementContext) DetachMemDiskTracker()

DetachMemDiskTracker detaches the memory and disk tracker from the sessionTracker.

func (*StatementContext) ErrCtx

func (sc *StatementContext) ErrCtx() errctx.Context

ErrCtx returns the error context

func (*StatementContext) ErrGroupLevel

func (sc *StatementContext) ErrGroupLevel(group errctx.ErrGroup) errctx.Level

ErrGroupLevel returns the error level for the given error group

func (*StatementContext) ErrLevels

func (sc *StatementContext) ErrLevels() errctx.LevelMap

ErrLevels returns the current `errctx.LevelMap`

func (*StatementContext) FoundRows

func (sc *StatementContext) FoundRows() uint64

FoundRows gets found rows.

func (*StatementContext) GetBinaryPlan

func (sc *StatementContext) GetBinaryPlan() string

GetBinaryPlan gets the binaryPlan field of stmtctx

func (*StatementContext) GetEncodedPlan

func (sc *StatementContext) GetEncodedPlan() string

GetEncodedPlan gets the encoded plan, it is used to avoid repeated encode.

func (*StatementContext) GetExecDetails

func (sc *StatementContext) GetExecDetails() execdetails.ExecDetails

GetExecDetails gets the execution details for the statement.

func (*StatementContext) GetExtraWarnings

func (sc *StatementContext) GetExtraWarnings() []SQLWarn

GetExtraWarnings gets extra warnings.

func (*StatementContext) GetFlatPlan

func (sc *StatementContext) GetFlatPlan() any

GetFlatPlan gets the flatPlan field of stmtctx

func (*StatementContext) GetIndexForce

func (sc *StatementContext) GetIndexForce() bool

GetIndexForce gets the IndexForce boolean generated from the plan.

func (*StatementContext) GetLockWaitStartTime

func (sc *StatementContext) GetLockWaitStartTime() time.Time

GetLockWaitStartTime returns the statement pessimistic lock wait start time

func (*StatementContext) GetMessage

func (sc *StatementContext) GetMessage() string

GetMessage returns the extra message of the last executed command, if there is no message, it returns empty string

func (*StatementContext) GetOrEvaluateStmtCache

func (sc *StatementContext) GetOrEvaluateStmtCache(key StmtCacheKey, valueEvaluator func() (any, error)) (any, error)

GetOrEvaluateStmtCache gets the cached value of the given key if it exists, otherwise calculate the value.

func (*StatementContext) GetOrInitBuildPBCtxFromCache

func (sc *StatementContext) GetOrInitBuildPBCtxFromCache(create func() any) any

GetOrInitBuildPBCtxFromCache returns the `BuildPBContext` inside cache. If it didn't exist, return a new one created by the `create` function. It uses the `any` to avoid cycle dependency.

func (*StatementContext) GetOrInitDistSQLFromCache

func (sc *StatementContext) GetOrInitDistSQLFromCache(create func() *distsqlctx.DistSQLContext) *distsqlctx.DistSQLContext

GetOrInitDistSQLFromCache returns the `DistSQLContext` inside cache. If it didn't exist, return a new one created by the `create` function.

func (*StatementContext) GetOrInitRangerCtxFromCache

func (sc *StatementContext) GetOrInitRangerCtxFromCache(create func() any) any

GetOrInitRangerCtxFromCache returns the `RangerContext` inside cache. If it didn't exist, return a new one created by the `create` function.

func (*StatementContext) GetOrStoreStmtCache

func (sc *StatementContext) GetOrStoreStmtCache(key StmtCacheKey, value any) any

GetOrStoreStmtCache gets the cached value of the given key if it exists, otherwise stores the value.

func (*StatementContext) GetPlan

func (sc *StatementContext) GetPlan() any

GetPlan gets the plan field of stmtctx

func (*StatementContext) GetPlanDigest

func (sc *StatementContext) GetPlanDigest() (normalized string, planDigest *parser.Digest)

GetPlanDigest gets the normalized plan and plan digest.

func (*StatementContext) GetPlanHint

func (sc *StatementContext) GetPlanHint() (string, bool)

GetPlanHint gets the hint string generated from the plan.

func (*StatementContext) GetResourceGroupTagger

func (sc *StatementContext) GetResourceGroupTagger() *kv.ResourceGroupTagBuilder

GetResourceGroupTagger returns the implementation of kv.ResourceGroupTagBuilder related to self.

func (*StatementContext) GetStaleTSO

func (sc *StatementContext) GetStaleTSO() (uint64, error)

GetStaleTSO returns the TSO for stale-read usage which calculate from PD's last response.

func (*StatementContext) GetUseChunkAllocStatus

func (sc *StatementContext) GetUseChunkAllocStatus() bool

GetUseChunkAllocStatus returns useChunkAlloc status

func (*StatementContext) GetUsedStatsInfo

func (sc *StatementContext) GetUsedStatsInfo(initIfNil bool) *UsedStatsInfo

GetUsedStatsInfo returns the map for recording the used stats during query. If initIfNil is true, it will initialize it when this map is nil.

func (*StatementContext) GetWarnings

func (sc *StatementContext) GetWarnings() []SQLWarn

GetWarnings gets warnings.

func (*StatementContext) HandleError

func (sc *StatementContext) HandleError(err error) error

HandleError handles the error based on `ErrCtx()`

func (*StatementContext) HandleErrorWithAlias

func (sc *StatementContext) HandleErrorWithAlias(internalErr, err, warnErr error) error

HandleErrorWithAlias handles the error based on `ErrCtx()`

func (*StatementContext) HandleTruncate

func (sc *StatementContext) HandleTruncate(err error) error

HandleTruncate ignores or returns the error based on the TypeContext inside. TODO: replace this function with `HandleError`, for `TruncatedError` they should have the same effect.

func (*StatementContext) InitDiskTracker

func (sc *StatementContext) InitDiskTracker(label int, bytesLimit int64)

InitDiskTracker initializes the sc.DiskTracker, use cache to avoid allocation.

func (*StatementContext) InitFromPBFlagAndTz

func (sc *StatementContext) InitFromPBFlagAndTz(flags uint64, tz *time.Location)

InitFromPBFlagAndTz set the flag and timezone of StatementContext from a `tipb.SelectRequest.Flags` and `*time.Location`.

func (*StatementContext) InitMemTracker

func (sc *StatementContext) InitMemTracker(label int, bytesLimit int64)

InitMemTracker initializes the sc.MemTracker, use cache to avoid allocation.

func (*StatementContext) InitSQLDigest

func (sc *StatementContext) InitSQLDigest(normalized string, digest *parser.Digest)

InitSQLDigest sets the normalized and digest for sql.

func (*StatementContext) NumErrorWarnings

func (sc *StatementContext) NumErrorWarnings() (ec uint16, wc int)

NumErrorWarnings gets warning and error count.

func (*StatementContext) PushDownFlags

func (sc *StatementContext) PushDownFlags() uint64

PushDownFlags converts StatementContext to tipb.SelectRequest.Flags.

func (*StatementContext) RecordRows

func (sc *StatementContext) RecordRows() uint64

RecordRows is used to generate info message

func (*StatementContext) RecordedStatsLoadStatusCnt

func (sc *StatementContext) RecordedStatsLoadStatusCnt() (cnt int)

RecordedStatsLoadStatusCnt returns the total number of recorded column/index stats status, which is not full loaded.

func (*StatementContext) Reset

func (sc *StatementContext) Reset()

Reset resets a statement context

func (*StatementContext) ResetForRetry

func (sc *StatementContext) ResetForRetry()

ResetForRetry resets the changed states during execution.

func (*StatementContext) ResetInStmtCache

func (sc *StatementContext) ResetInStmtCache(key StmtCacheKey)

ResetInStmtCache resets the cache of given key.

func (*StatementContext) ResetSQLDigest

func (sc *StatementContext) ResetSQLDigest(s string)

ResetSQLDigest sets the normalized and digest for sql anyway, **DO NOT USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING NOW**.

func (*StatementContext) ResetStmtCache

func (sc *StatementContext) ResetStmtCache()

ResetStmtCache resets all cached values.

func (*StatementContext) SQLDigest

func (sc *StatementContext) SQLDigest() (normalized string, sqlDigest *parser.Digest)

SQLDigest gets normalized and digest for provided sql. it will cache result after first calling.

func (*StatementContext) SetAffectedRows

func (sc *StatementContext) SetAffectedRows(rows uint64)

SetAffectedRows sets affected rows.

func (*StatementContext) SetBinaryPlan

func (sc *StatementContext) SetBinaryPlan(binaryPlan string)

SetBinaryPlan sets the binaryPlan field of stmtctx

func (*StatementContext) SetEncodedPlan

func (sc *StatementContext) SetEncodedPlan(encodedPlan string)

SetEncodedPlan sets the encoded plan, it is used to avoid repeated encode.

func (*StatementContext) SetErrLevels

func (sc *StatementContext) SetErrLevels(otherLevels errctx.LevelMap)

SetErrLevels sets the error levels for statement The argument otherLevels is used to set the error levels except truncate

func (*StatementContext) SetExtraWarnings

func (sc *StatementContext) SetExtraWarnings(warns []SQLWarn)

SetExtraWarnings sets extra warnings.

func (*StatementContext) SetFlatPlan

func (sc *StatementContext) SetFlatPlan(flat any)

SetFlatPlan sets the flatPlan field of stmtctx

func (*StatementContext) SetHintWarning

func (sc *StatementContext) SetHintWarning(reason string)

SetHintWarning sets the hint warning and records the reason.

func (*StatementContext) SetHintWarningFromError

func (sc *StatementContext) SetHintWarningFromError(reason error)

SetHintWarningFromError sets the hint warning and records the reason.

func (*StatementContext) SetIndexForce

func (sc *StatementContext) SetIndexForce()

SetIndexForce sets the hint for the plan.

func (*StatementContext) SetMessage

func (sc *StatementContext) SetMessage(msg string)

SetMessage sets the info message generated by some commands

func (*StatementContext) SetPlan

func (sc *StatementContext) SetPlan(plan any)

SetPlan sets the plan field of stmtctx

func (*StatementContext) SetPlanDigest

func (sc *StatementContext) SetPlanDigest(normalized string, planDigest *parser.Digest)

SetPlanDigest sets the normalized plan and plan digest.

func (*StatementContext) SetPlanHint

func (sc *StatementContext) SetPlanHint(hint string)

SetPlanHint sets the hint for the plan.

func (*StatementContext) SetStaleTSOProvider

func (sc *StatementContext) SetStaleTSOProvider(eval func() (uint64, error))

SetStaleTSOProvider sets the stale TSO provider.

func (*StatementContext) SetTimeZone

func (sc *StatementContext) SetTimeZone(tz *time.Location)

SetTimeZone sets the timezone

func (*StatementContext) SetTypeFlags

func (sc *StatementContext) SetTypeFlags(flags types.Flags)

SetTypeFlags sets the type flags

func (*StatementContext) SetUseChunkAlloc

func (sc *StatementContext) SetUseChunkAlloc()

SetUseChunkAlloc set use chunk alloc status

func (*StatementContext) SetWarnings

func (sc *StatementContext) SetWarnings(warns []SQLWarn)

SetWarnings sets warnings.

func (*StatementContext) TimeZone

func (sc *StatementContext) TimeZone() *time.Location

TimeZone returns the timezone of the type context

func (*StatementContext) TouchedRows

func (sc *StatementContext) TouchedRows() uint64

TouchedRows is used to generate info message

func (*StatementContext) TruncateWarnings

func (sc *StatementContext) TruncateWarnings(start int) []SQLWarn

TruncateWarnings truncates warnings begin from start and returns the truncated warnings.

func (*StatementContext) TypeCtx

func (sc *StatementContext) TypeCtx() types.Context

TypeCtx returns the type context

func (*StatementContext) TypeCtxOrDefault

func (sc *StatementContext) TypeCtxOrDefault() types.Context

TypeCtxOrDefault returns the reference to the `TypeCtx` inside the statement context. If the statement context is nil, it'll return a newly created default type context. **don't** use this function if you can make sure the `sc` is not nil. We should limit the usage of this function as little as possible.

func (*StatementContext) TypeFlags

func (sc *StatementContext) TypeFlags() types.Flags

TypeFlags returns the type flags

func (*StatementContext) UpdatedRows

func (sc *StatementContext) UpdatedRows() uint64

UpdatedRows is used to generate info message

func (*StatementContext) UseDynamicPartitionPrune

func (sc *StatementContext) UseDynamicPartitionPrune() bool

UseDynamicPartitionPrune indicates whether dynamic partition is used during the query

func (*StatementContext) WarningCount

func (sc *StatementContext) WarningCount() uint16

WarningCount gets warning count.

type StatsLoadResult

type StatsLoadResult struct {
	Item  model.TableItemID
	Error error
}

StatsLoadResult indicates result for StatsLoad

func (StatsLoadResult) ErrorMsg

func (r StatsLoadResult) ErrorMsg() string

ErrorMsg returns StatsLoadResult err msg

func (StatsLoadResult) HasError

func (r StatsLoadResult) HasError() bool

HasError returns whether result has error

type StmtCacheKey

type StmtCacheKey int

StmtCacheKey represents the key type in the StmtCache.

const (
	// StmtNowTsCacheKey is a variable for now/current_timestamp calculation/cache of one stmt.
	StmtNowTsCacheKey StmtCacheKey = iota
	// StmtSafeTSCacheKey is a variable for safeTS calculation/cache of one stmt.
	StmtSafeTSCacheKey
	// StmtExternalTSCacheKey is a variable for externalTS calculation/cache of one stmt.
	StmtExternalTSCacheKey
)

type TableEntry

type TableEntry struct {
	DB    string
	Table string
}

TableEntry presents table in db.

type UsedStatsInfo

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

UsedStatsInfo is a map for recording the used stats during query. The key is the table ID, and the value is the used stats info for the table.

func (*UsedStatsInfo) GetUsedInfo

func (u *UsedStatsInfo) GetUsedInfo(tableID int64) *UsedStatsInfoForTable

GetUsedInfo gets the used stats info for the table.

func (*UsedStatsInfo) Keys

func (u *UsedStatsInfo) Keys() []int64

Keys returns all the table IDs for the used stats info.

func (*UsedStatsInfo) RecordUsedInfo

func (u *UsedStatsInfo) RecordUsedInfo(tableID int64, info *UsedStatsInfoForTable)

RecordUsedInfo records the used stats info for the table.

func (*UsedStatsInfo) Values

func (u *UsedStatsInfo) Values() []*UsedStatsInfoForTable

Values returns all the used stats info for the table.

type UsedStatsInfoForTable

type UsedStatsInfoForTable struct {
	Name                  string
	TblInfo               *model.TableInfo
	Version               uint64
	RealtimeCount         int64
	ModifyCount           int64
	ColumnStatsLoadStatus map[int64]string
	IndexStatsLoadStatus  map[int64]string
	ColAndIdxStatus       any
}

UsedStatsInfoForTable records stats that are used during query and their information.

func (*UsedStatsInfoForTable) FormatForExplain

func (s *UsedStatsInfoForTable) FormatForExplain() string

FormatForExplain format the content in the format expected to be printed in the execution plan. case 1: if stats version is 0, print stats:pseudo. case 2: if stats version is not 0, and there are column/index stats that are not full loaded, print stats:partial, then print status of 3 column/index status at most. For the rest, only the count will be printed, in the format like (more: 1 onlyCmsEvicted, 2 onlyHistRemained).

func (*UsedStatsInfoForTable) WriteToSlowLog

func (s *UsedStatsInfoForTable) WriteToSlowLog(w io.Writer)

WriteToSlowLog format the content in the format expected to be printed to the slow log, then write to w. The format is table name partition name:version[realtime row count;modify count][index load status][column load status].

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL