variable

package
v1.1.0-beta.0...-9971301 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2025 License: Apache-2.0 Imports: 83 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ConnTypeSocket indicates socket without TLS.
	ConnTypeSocket string = "TCP"
	// ConnTypeUnixSocket indicates Unix Socket.
	ConnTypeUnixSocket string = "UnixSocket"
	// ConnTypeTLS indicates socket with TLS.
	ConnTypeTLS string = "SSL/TLS"
)
View Source
const (
	// SlowLogRowPrefixStr is slow log row prefix.
	SlowLogRowPrefixStr = "# "
	// SlowLogSpaceMarkStr is slow log space mark.
	SlowLogSpaceMarkStr = ": "
	// SlowLogSQLSuffixStr is slow log suffix.
	SlowLogSQLSuffixStr = ";"
	// SlowLogTimeStr is slow log field name.
	SlowLogTimeStr = "Time"
	// SlowLogStartPrefixStr is slow log start row prefix.
	SlowLogStartPrefixStr = SlowLogRowPrefixStr + SlowLogTimeStr + SlowLogSpaceMarkStr
	// SlowLogTxnStartTSStr is slow log field name.
	SlowLogTxnStartTSStr = "Txn_start_ts"
	// SlowLogKeyspaceName is slow log field name.
	SlowLogKeyspaceName = "Keyspace_name"
	// SlowLogKeyspaceID is slow log field name.
	SlowLogKeyspaceID = "Keyspace_ID"
	// SlowLogUserAndHostStr is the user and host field name, which is compatible with MySQL.
	SlowLogUserAndHostStr = "User@Host"
	// SlowLogUserStr is slow log field name.
	SlowLogUserStr = "User"
	// SlowLogHostStr only for slow_query table usage.
	SlowLogHostStr = "Host"
	// SlowLogConnIDStr is slow log field name.
	SlowLogConnIDStr = "Conn_ID"
	// SlowLogSessAliasStr is the session alias set by user
	SlowLogSessAliasStr = "Session_alias"
	// SlowLogQueryTimeStr is slow log field name.
	SlowLogQueryTimeStr = "Query_time"
	// SlowLogParseTimeStr is the parse sql time.
	SlowLogParseTimeStr = "Parse_time"
	// SlowLogCompileTimeStr is the compile plan time.
	SlowLogCompileTimeStr = "Compile_time"
	// SlowLogRewriteTimeStr is the rewrite time.
	SlowLogRewriteTimeStr = "Rewrite_time"
	// SlowLogOptimizeTimeStr is the optimization time.
	SlowLogOptimizeTimeStr = "Optimize_time"
	// SlowLogWaitTSTimeStr is the time of waiting TS.
	SlowLogWaitTSTimeStr = "Wait_TS"
	// SlowLogPreprocSubQueriesStr is the number of pre-processed sub-queries.
	SlowLogPreprocSubQueriesStr = "Preproc_subqueries"
	// SlowLogPreProcSubQueryTimeStr is the total time of pre-processing sub-queries.
	SlowLogPreProcSubQueryTimeStr = "Preproc_subqueries_time"
	// SlowLogDBStr is slow log field name.
	SlowLogDBStr = "DB"
	// SlowLogIsInternalStr is slow log field name.
	SlowLogIsInternalStr = "Is_internal"
	// SlowLogIndexNamesStr is slow log field name.
	SlowLogIndexNamesStr = "Index_names"
	// SlowLogDigestStr is slow log field name.
	SlowLogDigestStr = "Digest"
	// SlowLogQuerySQLStr is slow log field name.
	SlowLogQuerySQLStr = "Query" // use for slow log table, slow log will not print this field name but print sql directly.
	// SlowLogStatsInfoStr is plan stats info.
	SlowLogStatsInfoStr = "Stats"
	// SlowLogNumCopTasksStr is the number of cop-tasks.
	SlowLogNumCopTasksStr = "Num_cop_tasks"
	// SlowLogCopProcAvg is the average process time of all cop-tasks.
	SlowLogCopProcAvg = "Cop_proc_avg"
	// SlowLogCopProcP90 is the p90 process time of all cop-tasks.
	SlowLogCopProcP90 = "Cop_proc_p90"
	// SlowLogCopProcMax is the max process time of all cop-tasks.
	SlowLogCopProcMax = "Cop_proc_max"
	// SlowLogCopProcAddr is the address of TiKV where the cop-task which cost max process time run.
	SlowLogCopProcAddr = "Cop_proc_addr"
	// SlowLogCopWaitAvg is the average wait time of all cop-tasks.
	SlowLogCopWaitAvg = "Cop_wait_avg" // #nosec G101
	// SlowLogCopWaitP90 is the p90 wait time of all cop-tasks.
	SlowLogCopWaitP90 = "Cop_wait_p90" // #nosec G101
	// SlowLogCopWaitMax is the max wait time of all cop-tasks.
	SlowLogCopWaitMax = "Cop_wait_max"
	// SlowLogCopWaitAddr is the address of TiKV where the cop-task which cost wait process time run.
	SlowLogCopWaitAddr = "Cop_wait_addr" // #nosec G101
	// SlowLogCopBackoffPrefix contains backoff information.
	SlowLogCopBackoffPrefix = "Cop_backoff_"
	// SlowLogMemMax is the max number bytes of memory used in this statement.
	SlowLogMemMax = "Mem_max"
	// SlowLogDiskMax is the max number bytes of disk used in this statement.
	SlowLogDiskMax = "Disk_max"
	// SlowLogPrepared is used to indicate whether this sql execute in prepare.
	SlowLogPrepared = "Prepared"
	// SlowLogPlanFromCache is used to indicate whether this plan is from plan cache.
	SlowLogPlanFromCache = "Plan_from_cache"
	// SlowLogPlanFromBinding is used to indicate whether this plan is matched with the hints in the binding.
	SlowLogPlanFromBinding = "Plan_from_binding"
	// SlowLogHasMoreResults is used to indicate whether this sql has more following results.
	SlowLogHasMoreResults = "Has_more_results"
	// SlowLogSucc is used to indicate whether this sql execute successfully.
	SlowLogSucc = "Succ"
	// SlowLogPrevStmt is used to show the previous executed statement.
	SlowLogPrevStmt = "Prev_stmt"
	// SlowLogPlan is used to record the query plan.
	SlowLogPlan = "Plan"
	// SlowLogPlanDigest is used to record the query plan digest.
	SlowLogPlanDigest = "Plan_digest"
	// SlowLogBinaryPlan is used to record the binary plan.
	SlowLogBinaryPlan = "Binary_plan"
	// SlowLogPlanPrefix is the prefix of the plan value.
	SlowLogPlanPrefix = ast.TiDBDecodePlan + "('"
	// SlowLogBinaryPlanPrefix is the prefix of the binary plan value.
	SlowLogBinaryPlanPrefix = ast.TiDBDecodeBinaryPlan + "('"
	// SlowLogPlanSuffix is the suffix of the plan value.
	SlowLogPlanSuffix = "')"
	// SlowLogPrevStmtPrefix is the prefix of Prev_stmt in slow log file.
	SlowLogPrevStmtPrefix = SlowLogPrevStmt + SlowLogSpaceMarkStr
	// SlowLogKVTotal is the total time waiting for kv.
	SlowLogKVTotal = "KV_total"
	// SlowLogPDTotal is the total time waiting for pd.
	SlowLogPDTotal = "PD_total"
	// SlowLogBackoffTotal is the total time doing backoff.
	SlowLogBackoffTotal = "Backoff_total"
	// SlowLogUnpackedBytesSentTiKVTotal is the total bytes sent by tikv.
	SlowLogUnpackedBytesSentTiKVTotal = "Unpacked_bytes_sent_tikv_total"
	// SlowLogUnpackedBytesReceivedTiKVTotal is the total bytes received by tikv.
	SlowLogUnpackedBytesReceivedTiKVTotal = "Unpacked_bytes_received_tikv_total"
	// SlowLogUnpackedBytesSentTiKVCrossZone is the cross zone bytes sent by tikv.
	SlowLogUnpackedBytesSentTiKVCrossZone = "Unpacked_bytes_sent_tikv_cross_zone"
	// SlowLogUnpackedBytesReceivedTiKVCrossZone is the cross zone bytes received by tikv.
	SlowLogUnpackedBytesReceivedTiKVCrossZone = "Unpacked_bytes_received_tikv_cross_zone"
	// SlowLogUnpackedBytesSentTiFlashTotal is the total bytes sent by tiflash.
	SlowLogUnpackedBytesSentTiFlashTotal = "Unpacked_bytes_sent_tiflash_total"
	// SlowLogUnpackedBytesReceivedTiFlashTotal is the total bytes received by tiflash.
	SlowLogUnpackedBytesReceivedTiFlashTotal = "Unpacked_bytes_received_tiflash_total"
	// SlowLogUnpackedBytesSentTiFlashCrossZone is the cross zone bytes sent by tiflash.
	SlowLogUnpackedBytesSentTiFlashCrossZone = "Unpacked_bytes_sent_tiflash_cross_zone"
	// SlowLogUnpackedBytesReceivedTiFlashCrossZone is the cross zone bytes received by tiflash.
	SlowLogUnpackedBytesReceivedTiFlashCrossZone = "Unpacked_bytes_received_tiflash_cross_zone"
	// SlowLogWriteSQLRespTotal is the total time used to write response to client.
	SlowLogWriteSQLRespTotal = "Write_sql_response_total"
	// SlowLogExecRetryCount is the execution retry count.
	SlowLogExecRetryCount = "Exec_retry_count"
	// SlowLogExecRetryTime is the execution retry time.
	SlowLogExecRetryTime = "Exec_retry_time"
	// SlowLogBackoffDetail is the detail of backoff.
	SlowLogBackoffDetail = "Backoff_Detail"
	// SlowLogResultRows is the row count of the SQL result.
	SlowLogResultRows = "Result_rows"
	// SlowLogWarnings is the warnings generated during executing the statement.
	// Note that some extra warnings would also be printed through slow log.
	SlowLogWarnings = "Warnings"
	// SlowLogIsExplicitTxn is used to indicate whether this sql execute in explicit transaction or not.
	SlowLogIsExplicitTxn = "IsExplicitTxn"
	// SlowLogIsWriteCacheTable is used to indicate whether writing to the cache table need to wait for the read lock to expire.
	SlowLogIsWriteCacheTable = "IsWriteCacheTable"
	// SlowLogIsSyncStatsFailed is used to indicate whether any failure happen during sync stats
	SlowLogIsSyncStatsFailed = "IsSyncStatsFailed"
	// SlowLogResourceGroup is the resource group name that the current session bind.
	SlowLogResourceGroup = "Resource_group"
	// SlowLogRRU is the read request_unit(RU) cost
	SlowLogRRU = "Request_unit_read"
	// SlowLogWRU is the write request_unit(RU) cost
	SlowLogWRU = "Request_unit_write"
	// SlowLogWaitRUDuration is the total duration for kv requests to wait available request-units.
	SlowLogWaitRUDuration = "Time_queued_by_rc"
	// SlowLogTidbCPUUsageDuration is the total tidb cpu usages.
	SlowLogTidbCPUUsageDuration = "Tidb_cpu_time"
	// SlowLogTikvCPUUsageDuration is the total tikv cpu usages.
	SlowLogTikvCPUUsageDuration = "Tikv_cpu_time"
)
View Source
const (
	// OffInt is used by TiDBOptOnOffWarn
	OffInt = 0
	// OnInt is used TiDBOptOnOffWarn
	OnInt = 1
	// WarnInt is used by TiDBOptOnOffWarn
	WarnInt = 2
)
View Source
const ConnStatusShutdown int32 = 2

ConnStatusShutdown indicates that the connection status is closed by server. This code is put here because of package imports, and this value is the original server.connStatusShutdown.

Variables

View Source
var (
	ErrSnapshotTooOld              = dbterror.ClassVariable.NewStd(mysql.ErrSnapshotTooOld)
	ErrUnsupportedValueForVar      = dbterror.ClassVariable.NewStd(mysql.ErrUnsupportedValueForVar)
	ErrUnknownSystemVar            = dbterror.ClassVariable.NewStd(mysql.ErrUnknownSystemVariable)
	ErrIncorrectScope              = dbterror.ClassVariable.NewStd(mysql.ErrIncorrectGlobalLocalVar)
	ErrUnknownTimeZone             = dbterror.ClassVariable.NewStd(mysql.ErrUnknownTimeZone)
	ErrReadOnly                    = dbterror.ClassVariable.NewStd(mysql.ErrVariableIsReadonly)
	ErrWrongValueForVar            = dbterror.ClassVariable.NewStd(mysql.ErrWrongValueForVar)
	ErrWrongTypeForVar             = dbterror.ClassVariable.NewStd(mysql.ErrWrongTypeForVar)
	ErrTruncatedWrongValue         = dbterror.ClassVariable.NewStd(mysql.ErrTruncatedWrongValue)
	ErrMaxPreparedStmtCountReached = dbterror.ClassVariable.NewStd(mysql.ErrMaxPreparedStmtCountReached)
	ErrUnsupportedIsolationLevel   = dbterror.ClassVariable.NewStd(mysql.ErrUnsupportedIsolationLevel)

	ErrNotValidPassword = dbterror.ClassExecutor.NewStd(mysql.ErrNotValidPassword)
	// ErrFunctionsNoopImpl is an error to say the behavior is protected by the tidb_enable_noop_functions sysvar.
	// This is copied from expression.ErrFunctionsNoopImpl to prevent circular dependencies.
	// It needs to be public for tests.
	ErrFunctionsNoopImpl                 = dbterror.ClassVariable.NewStdErr(mysql.ErrNotSupportedYet, pmysql.Message("function %s has only noop implementation in tidb now, use tidb_enable_noop_functions to enable these functions", nil))
	ErrVariableNoLongerSupported         = dbterror.ClassVariable.NewStd(mysql.ErrVariableNoLongerSupported)
	ErrInvalidDefaultUTF8MB4Collation    = dbterror.ClassVariable.NewStd(mysql.ErrInvalidDefaultUTF8MB4Collation)
	ErrWarnDeprecatedSyntaxNoReplacement = dbterror.ClassVariable.NewStdErr(mysql.ErrWarnDeprecatedSyntaxNoReplacement, pmysql.Message("Updating '%s' is deprecated. It will be made read-only in a future release.", nil))
	ErrWarnDeprecatedSyntaxSimpleMsg     = dbterror.ClassVariable.NewStdErr(mysql.ErrWarnDeprecatedSyntaxNoReplacement, pmysql.Message("%s is deprecated and will be removed in a future release.", nil))
)

Error instances.

View Source
var (
	// SetMemQuotaAnalyze is the func registered by global/subglobal tracker to set memory quota.
	SetMemQuotaAnalyze func(quota int64) = nil
	// GetMemQuotaAnalyze is the func registered by global/subglobal tracker to get memory quota.
	GetMemQuotaAnalyze func() int64 = nil
	// SetStatsCacheCapacity is the func registered by domain to set statsCache memory quota.
	SetStatsCacheCapacity atomic.Pointer[func(int64)]
	// SetPDClientDynamicOption is the func registered by domain
	SetPDClientDynamicOption atomic.Pointer[func(string, string) error]
	// SwitchMDL is the func registered by DDL to switch MDL.
	SwitchMDL func(bool2 bool) error = nil
	// EnableDDL is the func registered by ddl to enable running ddl in this instance.
	EnableDDL func() error = nil
	// DisableDDL is the func registered by ddl to disable running ddl in this instance.
	DisableDDL func() error = nil
	// SwitchFastCreateTable is the func registered by DDL to switch fast create table.
	SwitchFastCreateTable func(val bool) error
	// SetExternalTimestamp is the func registered by staleread to set externaltimestamp in pd
	SetExternalTimestamp func(ctx context.Context, ts uint64) error
	// GetExternalTimestamp is the func registered by staleread to get externaltimestamp from pd
	GetExternalTimestamp func(ctx context.Context) (uint64, error)
	// SetGlobalResourceControl is the func registered by domain to set cluster resource control.
	SetGlobalResourceControl atomic.Pointer[func(bool)]
	// ValidateCloudStorageURI validates the cloud storage URI.
	ValidateCloudStorageURI func(ctx context.Context, uri string) error
	// SetLowResolutionTSOUpdateInterval is the func registered by domain to set slow resolution tso update interval.
	SetLowResolutionTSOUpdateInterval func(interval time.Duration) error = nil
	// ChangeSchemaCacheSize is called when tidb_schema_cache_size is changed.
	ChangeSchemaCacheSize func(ctx context.Context, size uint64) error
	// EnableStatsOwner is the func registered by stats to enable running stats in this instance.
	EnableStatsOwner func() error = nil
	// DisableStatsOwner is the func registered by stats to disable running stats in this instance.
	DisableStatsOwner func() error = nil
	// ChangePDMetadataCircuitBreakerErrorRateThresholdPct changes the error rate threshold of the PD metadata circuit breaker.
	ChangePDMetadataCircuitBreakerErrorRateThresholdPct func(uint32) = nil
)
View Source
var (
	// EnableGlobalResourceControlFunc is the function registered by tikv_driver to set cluster resource control.
	EnableGlobalResourceControlFunc = func() {}
	// DisableGlobalResourceControlFunc is the function registered by tikv_driver to unset cluster resource control.
	DisableGlobalResourceControlFunc = func() {}
)

Hooks functions for Cluster Resource Control.

View Source
var (
	// SchemaCacheSizeLowerBound will adjust the schema cache size to this value if
	// it is lower than this value.
	SchemaCacheSizeLowerBound uint64 = 64 * units.MiB
	// SchemaCacheSizeLowerBoundStr is the string representation of
	// SchemaCacheSizeLowerBound.
	SchemaCacheSizeLowerBoundStr = "64MB"
)
View Source
var DefaultStatusVarScopeFlag = vardef.ScopeGlobal | vardef.ScopeSession

DefaultStatusVarScopeFlag is the default scope of status variables.

GAFunction4ExpressionIndex stores functions GA for expression index.

View Source
var GenerateBinaryPlan atomic2.Bool

GenerateBinaryPlan decides whether we should record binary plan in slow log and stmt summary. It's controlled by the global variable `tidb_generate_binary_plan`.

View Source
var (
	// PreparedStmtCount is exported for test.
	PreparedStmtCount int64
)

Functions

func BoolToOnOff

func BoolToOnOff(b bool) string

BoolToOnOff returns the string representation of a bool, i.e. "ON/OFF"

func CheckSysVarIsRemoved

func CheckSysVarIsRemoved(varName string) error

CheckSysVarIsRemoved returns an error if the sysvar has been removed

func GetStatusVars

func GetStatusVars(vars *SessionVars) (map[string]*StatusVal, error)

GetStatusVars gets registered statistics status variables. TODO: Refactor this function to avoid repeated memory allocation / dealloc

func GetSysVars

func GetSysVars() map[string]*SysVar

GetSysVars deep copies the sysVars list under a RWLock

func GlobalSystemVariableInitialValue

func GlobalSystemVariableInitialValue(varName, varVal string) string

GlobalSystemVariableInitialValue gets the default value for a system variable including ones that are dynamically set (e.g. based on the store)

func IsAdaptiveReplicaReadEnabled

func IsAdaptiveReplicaReadEnabled() bool

IsAdaptiveReplicaReadEnabled returns whether adaptive closest replica read can be enabled.

func IsRemovedSysVar

func IsRemovedSysVar(varName string) bool

IsRemovedSysVar returns true if the sysvar has been removed

func OnOffToTrueFalse

func OnOffToTrueFalse(str string) string

OnOffToTrueFalse convert "ON"/"OFF" to "true"/"false". In mysql.tidb the convention has been to store the string value "true"/"false", but sysvars use the convention ON/OFF.

func OrderByDependency

func OrderByDependency(names map[string]string) []string

OrderByDependency orders the vars by dependency. The depended sys vars are in the front. Unknown sys vars are treated as not depended.

func ParseAnalyzeSkipColumnTypes

func ParseAnalyzeSkipColumnTypes(val string) map[string]struct{}

ParseAnalyzeSkipColumnTypes converts tidb_analyze_skip_column_types to the map form.

func RegisterStatistics

func RegisterStatistics(s Statistics)

RegisterStatistics registers statistics.

func RegisterSysVar

func RegisterSysVar(sv *SysVar)

RegisterSysVar adds a sysvar to the SysVars list

func SetEnableAdaptiveReplicaRead

func SetEnableAdaptiveReplicaRead(enabled bool) bool

SetEnableAdaptiveReplicaRead set `enableAdaptiveReplicaRead` with given value. return true if the value is changed.

func SetSysVar

func SetSysVar(name string, value string)

SetSysVar sets a sysvar. In fact, SysVar is immutable. SetSysVar is implemented by register a new SysVar with the same name again. This will not propagate to the cluster, so it should only be used for instance scoped AUTO variables such as system_time_zone.

func TiDBOptOn

func TiDBOptOn(opt string) bool

TiDBOptOn could be used for all tidb session variable options, we use "ON"/1 to turn on those options.

func TiDBOptOnOffWarn

func TiDBOptOnOffWarn(opt string) int

TiDBOptOnOffWarn converts On/Off/Warn to an int. It is used for MultiStmtMode and NoopFunctionsMode

func TidbOptInt

func TidbOptInt(opt string, defaultVal int) int

TidbOptInt converts a string to an int

func TidbOptInt64

func TidbOptInt64(opt string, defaultVal int64) int64

TidbOptInt64 converts a string to an int64

func TidbOptUint64

func TidbOptUint64(opt string, defaultVal uint64) uint64

TidbOptUint64 converts a string to an uint64.

func ToTiPBTiFlashPreAggMode

func ToTiPBTiFlashPreAggMode(mode string) (tipb.TiFlashPreAggMode, bool)

ToTiPBTiFlashPreAggMode return the corresponding tipb value of preaggregation mode.

func UnregisterStatistics

func UnregisterStatistics(s Statistics)

UnregisterStatistics unregisters statistics.

func UnregisterSysVar

func UnregisterSysVar(name string)

UnregisterSysVar removes a sysvar from the SysVars list currently only used in tests.

func ValidAnalyzeSkipColumnTypes

func ValidAnalyzeSkipColumnTypes(val string) (string, error)

ValidAnalyzeSkipColumnTypes makes validation for tidb_analyze_skip_column_types.

func ValidTiFlashPreAggMode

func ValidTiFlashPreAggMode() string

ValidTiFlashPreAggMode returns all valid modes.

Types

type AssertionLevel

type AssertionLevel int

AssertionLevel controls the assertion that will be performed during transactions.

const (
	// AssertionLevelOff indicates no assertion should be performed.
	AssertionLevelOff AssertionLevel = iota
	// AssertionLevelFast indicates assertions that doesn't affect performance should be performed.
	AssertionLevelFast
	// AssertionLevelStrict indicates full assertions should be performed, even if the performance might be slowed down.
	AssertionLevelStrict
)

type BatchSize

type BatchSize struct {
	// IndexJoinBatchSize is the batch size of a index lookup join.
	IndexJoinBatchSize int

	// IndexLookupSize is the number of handles for an index lookup task in index double read executor.
	IndexLookupSize int

	// InitChunkSize defines init row count of a Chunk during query execution.
	InitChunkSize int

	// MaxChunkSize defines max row count of a Chunk during query execution.
	MaxChunkSize int

	// MinPagingSize defines the min size used by the coprocessor paging protocol.
	MinPagingSize int

	// MinPagingSize defines the max size used by the coprocessor paging protocol.
	MaxPagingSize int
}

BatchSize defines batch size values.

type Concurrency

type Concurrency struct {

	// ExecutorConcurrency is the number of concurrent worker for all executors.
	ExecutorConcurrency int

	// SourceAddr is the source address of request. Available in coprocessor ONLY.
	SourceAddr net.TCPAddr

	// IdleTransactionTimeout indicates the maximum time duration a transaction could be idle, unit is second.
	IdleTransactionTimeout int

	// BulkDMLEnabled indicates whether to enable bulk DML in pipelined mode.
	BulkDMLEnabled bool
	// contains filtered or unexported fields
}

Concurrency defines concurrency values.

func (*Concurrency) AnalyzeDistSQLScanConcurrency

func (c *Concurrency) AnalyzeDistSQLScanConcurrency() int

AnalyzeDistSQLScanConcurrency return the number of concurrent dist SQL scan worker when to analyze.

func (*Concurrency) DistSQLScanConcurrency

func (c *Concurrency) DistSQLScanConcurrency() int

DistSQLScanConcurrency return the number of concurrent dist SQL scan worker.

func (*Concurrency) HashAggFinalConcurrency

func (c *Concurrency) HashAggFinalConcurrency() int

HashAggFinalConcurrency return the number of concurrent hash aggregation final worker.

func (*Concurrency) HashAggPartialConcurrency

func (c *Concurrency) HashAggPartialConcurrency() int

HashAggPartialConcurrency return the number of concurrent hash aggregation partial worker.

func (*Concurrency) HashJoinConcurrency

func (c *Concurrency) HashJoinConcurrency() int

HashJoinConcurrency return the number of concurrent hash join outer worker.

func (*Concurrency) IndexLookupConcurrency

func (c *Concurrency) IndexLookupConcurrency() int

IndexLookupConcurrency return the number of concurrent index lookup worker.

func (*Concurrency) IndexLookupJoinConcurrency

func (c *Concurrency) IndexLookupJoinConcurrency() int

IndexLookupJoinConcurrency return the number of concurrent index lookup join inner worker.

func (*Concurrency) IndexMergeIntersectionConcurrency

func (c *Concurrency) IndexMergeIntersectionConcurrency() int

IndexMergeIntersectionConcurrency return the number of concurrent process worker.

func (*Concurrency) IndexSerialScanConcurrency

func (c *Concurrency) IndexSerialScanConcurrency() int

IndexSerialScanConcurrency return the number of concurrent index serial scan worker. This option is not sync with ExecutorConcurrency since it's used by Analyze table.

func (*Concurrency) MergeJoinConcurrency

func (c *Concurrency) MergeJoinConcurrency() int

MergeJoinConcurrency return the number of concurrent merge join worker.

func (*Concurrency) ProjectionConcurrency

func (c *Concurrency) ProjectionConcurrency() int

ProjectionConcurrency return the number of concurrent projection worker.

func (*Concurrency) SetAnalyzeDistSQLScanConcurrency

func (c *Concurrency) SetAnalyzeDistSQLScanConcurrency(n int)

SetAnalyzeDistSQLScanConcurrency set the number of concurrent dist SQL scan worker when to analyze.

func (*Concurrency) SetDistSQLScanConcurrency

func (c *Concurrency) SetDistSQLScanConcurrency(n int)

SetDistSQLScanConcurrency set the number of concurrent dist SQL scan worker.

func (*Concurrency) SetHashAggFinalConcurrency

func (c *Concurrency) SetHashAggFinalConcurrency(n int)

SetHashAggFinalConcurrency set the number of concurrent hash aggregation final worker.

func (*Concurrency) SetHashAggPartialConcurrency

func (c *Concurrency) SetHashAggPartialConcurrency(n int)

SetHashAggPartialConcurrency set the number of concurrent hash aggregation partial worker.

func (*Concurrency) SetHashJoinConcurrency

func (c *Concurrency) SetHashJoinConcurrency(n int)

SetHashJoinConcurrency set the number of concurrent hash join outer worker.

func (*Concurrency) SetIndexLookupConcurrency

func (c *Concurrency) SetIndexLookupConcurrency(n int)

SetIndexLookupConcurrency set the number of concurrent index lookup worker.

func (*Concurrency) SetIndexLookupJoinConcurrency

func (c *Concurrency) SetIndexLookupJoinConcurrency(n int)

SetIndexLookupJoinConcurrency set the number of concurrent index lookup join inner worker.

func (*Concurrency) SetIndexMergeIntersectionConcurrency

func (c *Concurrency) SetIndexMergeIntersectionConcurrency(n int)

SetIndexMergeIntersectionConcurrency set the number of concurrent intersection process worker.

func (*Concurrency) SetIndexSerialScanConcurrency

func (c *Concurrency) SetIndexSerialScanConcurrency(n int)

SetIndexSerialScanConcurrency set the number of concurrent index serial scan worker.

func (*Concurrency) SetMergeJoinConcurrency

func (c *Concurrency) SetMergeJoinConcurrency(n int)

SetMergeJoinConcurrency set the number of concurrent merge join worker.

func (*Concurrency) SetProjectionConcurrency

func (c *Concurrency) SetProjectionConcurrency(n int)

SetProjectionConcurrency set the number of concurrent projection worker.

func (*Concurrency) SetStreamAggConcurrency

func (c *Concurrency) SetStreamAggConcurrency(n int)

SetStreamAggConcurrency set the number of concurrent stream aggregation worker.

func (*Concurrency) SetWindowConcurrency

func (c *Concurrency) SetWindowConcurrency(n int)

SetWindowConcurrency set the number of concurrent window worker.

func (*Concurrency) StreamAggConcurrency

func (c *Concurrency) StreamAggConcurrency() int

StreamAggConcurrency return the number of concurrent stream aggregation worker.

func (*Concurrency) UnionConcurrency

func (c *Concurrency) UnionConcurrency() int

UnionConcurrency return the num of concurrent union worker.

func (*Concurrency) WindowConcurrency

func (c *Concurrency) WindowConcurrency() int

WindowConcurrency return the number of concurrent window worker.

type ConnectionInfo

type ConnectionInfo struct {
	ConnectionID      uint64
	ConnectionType    string
	Host              string
	ClientIP          string
	ClientPort        string
	ServerID          int
	ServerIP          string
	ServerPort        int
	Duration          float64
	User              string
	ServerOSLoginUser string
	OSVersion         string
	ClientVersion     string
	ServerVersion     string
	SSLVersion        string
	PID               int
	DB                string
	AuthMethod        string
	Attributes        map[string]string
}

ConnectionInfo presents the connection information, which is mainly used by audit logs.

func (*ConnectionInfo) IsSecureTransport

func (connInfo *ConnectionInfo) IsSecureTransport() bool

IsSecureTransport checks whether the connection is secure.

type GlobalVarAccessor

type GlobalVarAccessor interface {
	// GetGlobalSysVar gets the global system variable value for name.
	GetGlobalSysVar(name string) (string, error)
	// SetGlobalSysVar sets the global system variable name to value.
	SetGlobalSysVar(ctx context.Context, name string, value string) error
	// SetGlobalSysVarOnly sets the global system variable without calling the validation function or updating aliases.
	SetGlobalSysVarOnly(ctx context.Context, name string, value string, updateLocal bool) error
	// GetTiDBTableValue gets a value from mysql.tidb for the key 'name'
	GetTiDBTableValue(name string) (string, error)
	// SetTiDBTableValue sets a value+comment for the mysql.tidb key 'name'
	SetTiDBTableValue(name, value, comment string) error
}

GlobalVarAccessor is the interface for accessing global scope system and status variables.

type HookContext

type HookContext interface {
	GetStore() kv.Storage
}

HookContext contains the necessary variables for executing set/get hook

type JSONSQLWarnForSlowLog

type JSONSQLWarnForSlowLog struct {
	Level   string
	Message string
	// IsExtra means this SQL Warn is expected to be recorded only under some conditions (like in EXPLAIN) and should
	// haven't been recorded as a warning now, but we recorded it anyway to help diagnostics.
	IsExtra bool `json:",omitempty"`
}

JSONSQLWarnForSlowLog helps to print the SQLWarn through the slow log in JSON format.

type LazyStmtText

type LazyStmtText struct {
	SQL    string
	Redact string
	Params PlanCacheParamList
	Format func(string) string
	// contains filtered or unexported fields
}

LazyStmtText represents the sql text of a stmt that used in log. It's lazily evaluated to reduce the mem allocs.

func (*LazyStmtText) SetText

func (s *LazyStmtText) SetText(text string)

SetText sets the text directly.

func (*LazyStmtText) String

func (s *LazyStmtText) String() string

String implements fmt.Stringer.

func (*LazyStmtText) Update

func (s *LazyStmtText) Update(redact string, sql string, params *PlanCacheParamList)

Update resets the lazy text and leads to re-eval for next `s.String()`. It copies params so it's safe to use `SessionVars.PlanCacheParams` directly without worrying about the params get reset later.

type MemQuota

type MemQuota struct {
	// MemQuotaQuery defines the memory quota for a query.
	MemQuotaQuery int64
	// MemQuotaApplyCache defines the memory capacity for apply cache.
	MemQuotaApplyCache int64
}

MemQuota defines memory quota values.

type MockGlobalAccessor

type MockGlobalAccessor struct {
	SessionVars *SessionVars // can be overwritten if needed for correctness.
	// contains filtered or unexported fields
}

MockGlobalAccessor implements GlobalVarAccessor interface. it's used in tests

func NewMockGlobalAccessor

func NewMockGlobalAccessor() *MockGlobalAccessor

NewMockGlobalAccessor implements GlobalVarAccessor interface.

func NewMockGlobalAccessor4Tests

func NewMockGlobalAccessor4Tests() *MockGlobalAccessor

NewMockGlobalAccessor4Tests creates a new MockGlobalAccessor for use in the testsuite. It behaves like the real GlobalVarAccessor and has a list of sessionvars. Because we use the real GlobalVarAccessor outside of tests, this is unsafe to use by default (performance regression).

func (*MockGlobalAccessor) GetGlobalSysVar

func (m *MockGlobalAccessor) GetGlobalSysVar(name string) (string, error)

GetGlobalSysVar implements GlobalVarAccessor.GetGlobalSysVar interface.

func (*MockGlobalAccessor) GetTiDBTableValue

func (m *MockGlobalAccessor) GetTiDBTableValue(name string) (string, error)

GetTiDBTableValue implements GlobalVarAccessor.GetTiDBTableValue interface.

func (*MockGlobalAccessor) SetGlobalSysVar

func (m *MockGlobalAccessor) SetGlobalSysVar(ctx context.Context, name string, value string) (err error)

SetGlobalSysVar implements GlobalVarAccessor.SetGlobalSysVar interface.

func (*MockGlobalAccessor) SetGlobalSysVarOnly

func (m *MockGlobalAccessor) SetGlobalSysVarOnly(ctx context.Context, name string, value string, _ bool) error

SetGlobalSysVarOnly implements GlobalVarAccessor.SetGlobalSysVarOnly interface.

func (*MockGlobalAccessor) SetTiDBTableValue

func (m *MockGlobalAccessor) SetTiDBTableValue(name, value, comment string) error

SetTiDBTableValue implements GlobalVarAccessor.SetTiDBTableValue interface.

type PartitionPruneMode

type PartitionPruneMode string

PartitionPruneMode presents the prune mode used.

const (
	// Static indicates only prune at plan phase.
	Static PartitionPruneMode = "static"
	// Dynamic indicates only prune at execute phase.
	Dynamic PartitionPruneMode = "dynamic"

	// StaticOnly is out-of-date.
	StaticOnly PartitionPruneMode = "static-only"
	// DynamicOnly is out-of-date.
	DynamicOnly PartitionPruneMode = "dynamic-only"
	// StaticButPrepareDynamic is out-of-date.
	StaticButPrepareDynamic PartitionPruneMode = "static-collect-dynamic"
)

func (PartitionPruneMode) Update

Update updates out-of-date PruneMode.

func (PartitionPruneMode) Valid

func (p PartitionPruneMode) Valid() bool

Valid indicate PruneMode is validated.

type PlanCacheParamList

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

PlanCacheParamList stores the parameters for plan cache. Use attached methods to access or modify parameter values instead of accessing them directly.

func NewPlanCacheParamList

func NewPlanCacheParamList() *PlanCacheParamList

NewPlanCacheParamList creates a new PlanCacheParams.

func (*PlanCacheParamList) AllParamValues

func (p *PlanCacheParamList) AllParamValues() []types.Datum

AllParamValues returns all parameter values.

func (*PlanCacheParamList) Append

func (p *PlanCacheParamList) Append(vs ...types.Datum)

Append appends a parameter value to the PlanCacheParams.

func (*PlanCacheParamList) GetParamValue

func (p *PlanCacheParamList) GetParamValue(idx int) types.Datum

GetParamValue returns the value of the parameter at the specified index.

func (*PlanCacheParamList) Reset

func (p *PlanCacheParamList) Reset()

Reset resets the PlanCacheParams.

func (*PlanCacheParamList) SetForNonPrepCache

func (p *PlanCacheParamList) SetForNonPrepCache(flag bool)

SetForNonPrepCache sets the flag forNonPrepCache.

func (*PlanCacheParamList) String

func (p *PlanCacheParamList) String() string

String implements the fmt.Stringer interface.

type ReadConsistencyLevel

type ReadConsistencyLevel string

ReadConsistencyLevel is the level of read consistency.

const (
	// ReadConsistencyStrict means read by strict consistency, default value.
	ReadConsistencyStrict ReadConsistencyLevel = "strict"
	// ReadConsistencyWeak means read can be weak consistency.
	ReadConsistencyWeak ReadConsistencyLevel = "weak"
)

func (ReadConsistencyLevel) IsWeak

func (r ReadConsistencyLevel) IsWeak() bool

IsWeak returns true only if it's a weak-consistency read.

type RetryInfo

type RetryInfo struct {
	Retrying               bool
	DroppedPreparedStmtIDs []uint32

	LastRcReadTS uint64
	// contains filtered or unexported fields
}

RetryInfo saves retry information.

func (*RetryInfo) AddAutoIncrementID

func (r *RetryInfo) AddAutoIncrementID(id int64)

AddAutoIncrementID adds id to autoIncrementIDs.

func (*RetryInfo) AddAutoRandomID

func (r *RetryInfo) AddAutoRandomID(id int64)

AddAutoRandomID adds id to autoRandomIDs.

func (*RetryInfo) Clean

func (r *RetryInfo) Clean()

Clean does some clean work.

func (*RetryInfo) GetCurrAutoIncrementID

func (r *RetryInfo) GetCurrAutoIncrementID() (int64, bool)

GetCurrAutoIncrementID gets current autoIncrementID.

func (*RetryInfo) GetCurrAutoRandomID

func (r *RetryInfo) GetCurrAutoRandomID() (int64, bool)

GetCurrAutoRandomID gets current AutoRandomID.

func (*RetryInfo) ResetOffset

func (r *RetryInfo) ResetOffset()

ResetOffset resets the current retry offset.

type RewritePhaseInfo

type RewritePhaseInfo struct {
	// DurationRewrite is the duration of rewriting the SQL.
	DurationRewrite time.Duration

	// DurationPreprocessSubQuery is the duration of pre-processing sub-queries.
	DurationPreprocessSubQuery time.Duration

	// PreprocessSubQueries is the number of pre-processed sub-queries.
	PreprocessSubQueries int
}

RewritePhaseInfo records some information about the rewrite phase

func (*RewritePhaseInfo) Reset

func (r *RewritePhaseInfo) Reset()

Reset resets all fields in RewritePhaseInfo.

type RowIDShardGenerator

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

RowIDShardGenerator is used to generate shard for row id.

func NewRowIDShardGenerator

func NewRowIDShardGenerator(shardRand *rand.Rand, step int) *RowIDShardGenerator

NewRowIDShardGenerator creates a new RowIDShardGenerator.

func (*RowIDShardGenerator) GetCurrentShard

func (s *RowIDShardGenerator) GetCurrentShard(count int) int64

GetCurrentShard returns the shard for the next `count` IDs.

func (*RowIDShardGenerator) GetShardStep

func (s *RowIDShardGenerator) GetShardStep() int

GetShardStep returns the shard step

func (*RowIDShardGenerator) SetShardStep

func (s *RowIDShardGenerator) SetShardStep(step int)

SetShardStep sets the step of shard

type RuntimeFilterMode

type RuntimeFilterMode int64

RuntimeFilterMode the mode of runtime filter "OFF", "LOCAL"

const (
	RFOff RuntimeFilterMode = iota + 1
	RFLocal
	RFGlobal
)

RFOff disable runtime filter RFLocal enable local runtime filter RFGlobal enable local and global runtime filter

func RuntimeFilterModeStringToMode

func RuntimeFilterModeStringToMode(name string) (RuntimeFilterMode, bool)

RuntimeFilterModeStringToMode convert RuntimeFilterModeString to RuntimeFilterMode If name is legal, it will return Runtime Filter Mode and true Else, it will return -1 and false The second param means the convert is ok or not. True is ok, false means it is illegal name At present, we only support one name: "OFF", "LOCAL"

func (RuntimeFilterMode) String

func (rfMode RuntimeFilterMode) String() string

String convert Runtime Filter Mode to String name

type RuntimeFilterType

type RuntimeFilterType int64

RuntimeFilterType type of runtime filter "IN"

const (
	In RuntimeFilterType = iota
	MinMax
)

In type of runtime filter, like "t.k1 in (?)" MinMax type of runtime filter, like "t.k1 < ? and t.k1 > ?"

func RuntimeFilterTypeStringToType

func RuntimeFilterTypeStringToType(name string) (RuntimeFilterType, bool)

RuntimeFilterTypeStringToType convert RuntimeFilterTypeNameString to RuntimeFilterType If name is legal, it will return Runtime Filter Type and true Else, it will return -1 and false The second param means the convert is ok or not. True is ok, false means it is illegal name At present, we only support two names: "IN" and "MIN_MAX"

func ToRuntimeFilterType

func ToRuntimeFilterType(sessionVarValue string) ([]RuntimeFilterType, bool)

ToRuntimeFilterType convert session var value to RuntimeFilterType list If sessionVarValue is legal, it will return RuntimeFilterType list and true The second param means the convert is ok or not. True is ok, false means it is illegal value The legal value should be comma-separated, eg: "IN,MIN_MAX"

func (RuntimeFilterType) String

func (rfType RuntimeFilterType) String() string

String convert Runtime Filter Type to String name

type SavepointRecord

type SavepointRecord struct {
	// name is the name of the savepoint
	Name string
	// MemDBCheckpoint is the transaction's memdb checkpoint.
	MemDBCheckpoint *tikv.MemDBCheckpoint
	// TxnCtxSavepoint is the savepoint of TransactionContext
	TxnCtxSavepoint TxnCtxNeedToRestore
}

SavepointRecord indicates a transaction's savepoint record.

type SequenceState

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

SequenceState cache all sequence's latest value accessed by lastval() builtins. It's a session scoped variable, and all public methods of SequenceState are currently-safe.

func NewSequenceState

func NewSequenceState() *SequenceState

NewSequenceState creates a SequenceState.

func (*SequenceState) GetAllStates

func (ss *SequenceState) GetAllStates() map[int64]int64

GetAllStates returns a copied latestValueMap.

func (*SequenceState) GetLastValue

func (ss *SequenceState) GetLastValue(sequenceID int64) (int64, bool, error)

GetLastValue will return last value of the specified sequenceID, bool(true) indicates the sequenceID is not in the cache map and NULL will be returned.

func (*SequenceState) SetAllStates

func (ss *SequenceState) SetAllStates(latestValueMap map[int64]int64)

SetAllStates sets latestValueMap as a whole.

func (*SequenceState) UpdateState

func (ss *SequenceState) UpdateState(sequenceID, value int64)

UpdateState will update the last value of specified sequenceID in a session.

type SessionVars

type SessionVars struct {
	Concurrency
	MemQuota
	BatchSize
	// DMLBatchSize indicates the number of rows batch-committed for a statement.
	// It will be used when using LOAD DATA or BatchInsert or BatchDelete is on.
	DMLBatchSize        int
	RetryLimit          int64
	DisableTxnAutoRetry bool
	*UserVars

	// SysWarningCount is the system variable "warning_count", because it is on the hot path, so we extract it from the systems
	SysWarningCount int
	// SysErrorCount is the system variable "error_count", because it is on the hot path, so we extract it from the systems
	SysErrorCount uint16

	// PreparedStmts stores prepared statement.
	PreparedStmts        map[uint32]any
	PreparedStmtNameToID map[string]uint32

	// Parameter values for plan cache.
	PlanCacheParams   *PlanCacheParamList
	LastUpdateTime4PC types.Time

	// The Cached Plan for this execution, it should be *plannercore.PlanCacheValue.
	PlanCacheValue any

	// ActiveRoles stores active roles for current user
	ActiveRoles []*auth.RoleIdentity

	RetryInfo *RetryInfo
	// TxnCtx Should be reset on transaction finished.
	TxnCtx *TransactionContext
	// TxnCtxMu is used to protect TxnCtx.
	TxnCtxMu sync.Mutex

	// TxnManager is used to manage txn context in session
	TxnManager any

	// KVVars is the variables for KV storage.
	KVVars *tikvstore.Variables

	// ShardRowIDBits is the number of shard bits for user table row ID.
	ShardRowIDBits uint64

	// PreSplitRegions is the number of regions that should be pre-split for the table.
	PreSplitRegions uint64

	// ClientCapability is client's capability.
	ClientCapability uint32

	// TLSConnectionState is the TLS connection state (nil if not using TLS).
	TLSConnectionState *tls.ConnectionState

	// ConnectionID is the connection id of the current session.
	ConnectionID uint64

	// SQLCPUUsages records tidb/tikv cpu usages for current sql
	SQLCPUUsages ppcpuusage.SQLCPUUsages

	// PlanID is the unique id of logical and physical plan.
	PlanID atomic.Int32

	// PlanColumnID is the unique id for column when building plan.
	PlanColumnID atomic.Int64

	// MapScalarSubQ maps the scalar sub queries from its ID to its struct.
	MapScalarSubQ []any

	// MapHashCode2UniqueID4ExtendedCol map the expr's hash code to specified unique ID.
	MapHashCode2UniqueID4ExtendedCol map[string]int

	// User is the user identity with which the session login.
	User *auth.UserIdentity

	// Port is the port of the connected socket
	Port string

	// CurrentDB is the default database of this session.
	CurrentDB string

	// CurrentDBChanged indicates if the CurrentDB has been updated, and if it is we should print it into
	// the slow log to make it be compatible with MySQL, https://github.com/pingcap/tidb/issues/17846.
	CurrentDBChanged bool

	// CommonGlobalLoaded indicates if common global variable has been loaded for this session.
	CommonGlobalLoaded bool

	// InRestrictedSQL indicates if the session is handling restricted SQL execution.
	InRestrictedSQL bool

	// SnapshotTS is used for reading history data. For simplicity, SnapshotTS only supports distsql request.
	SnapshotTS uint64

	// LastCommitTS is the commit_ts of the last successful transaction in this session.
	LastCommitTS uint64

	// TxnReadTS is used for staleness transaction, it provides next staleness transaction startTS.
	TxnReadTS *TxnReadTS

	// SnapshotInfoschema is used with SnapshotTS, when the schema version at snapshotTS less than current schema
	// version, we load an old version schema for query.
	SnapshotInfoschema any

	// GlobalVarsAccessor is used to set and get global variables.
	GlobalVarsAccessor GlobalVarAccessor

	// LastFoundRows is the number of found rows of last query statement
	LastFoundRows uint64

	// StmtCtx holds variables for current executing statement.
	StmtCtx *stmtctx.StatementContext

	// RefCountOfStmtCtx indicates the reference count of StmtCtx. When the
	// StmtCtx is accessed by other sessions, e.g. oom-alarm-handler/expensive-query-handler, add one first.
	// Note: this variable should be accessed and updated by atomic operations.
	RefCountOfStmtCtx stmtctx.ReferenceCount

	// AllowAggPushDown can be set to false to forbid aggregation push down.
	AllowAggPushDown bool

	// AllowDeriveTopN is used to enable/disable derived TopN optimization.
	AllowDeriveTopN bool

	// AllowCartesianBCJ means allow broadcast CARTESIAN join, 0 means not allow, 1 means allow broadcast CARTESIAN join
	// but the table size should under the broadcast threshold, 2 means allow broadcast CARTESIAN join even if the table
	// size exceeds the broadcast threshold
	AllowCartesianBCJ int

	// MPPOuterJoinFixedBuildSide means in MPP plan, always use right(left) table as build side for left(right) out join
	MPPOuterJoinFixedBuildSide bool

	// AllowDistinctAggPushDown can be set true to allow agg with distinct push down to tikv/tiflash.
	AllowDistinctAggPushDown bool

	// EnableSkewDistinctAgg can be set true to allow skew distinct aggregate rewrite
	EnableSkewDistinctAgg bool

	// Enable3StageDistinctAgg indicates whether to allow 3 stage distinct aggregate
	Enable3StageDistinctAgg bool

	// Enable3StageMultiDistinctAgg indicates whether to allow 3 stage multi distinct aggregate
	Enable3StageMultiDistinctAgg bool

	ExplainNonEvaledSubQuery bool

	// MultiStatementMode permits incorrect client library usage. Not recommended to be turned on.
	MultiStatementMode int

	// InMultiStmts indicates whether the statement is a multi-statement like `update t set a=1; update t set b=2;`.
	InMultiStmts bool

	// AllowWriteRowID variable is currently not recommended to be turned on.
	AllowWriteRowID bool

	// AllowBatchCop means if we should send batch coprocessor to TiFlash. Default value is 1, means to use batch cop in case of aggregation and join.
	// Value set to 2 means to force to send batch cop for any query. Value set to 0 means never use batch cop.
	AllowBatchCop int

	// HashExchangeWithNewCollation means if we support hash exchange when new collation is enabled.
	// Default value is `true`, means support hash exchange when new collation is enabled.
	// Value set to `false` means not use hash exchange when new collation is enabled.
	HashExchangeWithNewCollation bool

	// TiFlashMaxThreads is the maximum number of threads to execute the request which is pushed down to tiflash.
	// Default value is -1, means it will not be pushed down to tiflash.
	// If the value is bigger than -1, it will be pushed down to tiflash and used to create db context in tiflash.
	TiFlashMaxThreads int64

	// TiFlashMaxBytesBeforeExternalJoin is the maximum bytes used by a TiFlash join before spill to disk
	// Default value is -1, means it will not be pushed down to TiFlash
	// If the value is bigger than -1, it will be pushed down to TiFlash, and if the value is 0, it means
	// not limit and spill will never happen
	TiFlashMaxBytesBeforeExternalJoin int64

	// TiFlashMaxBytesBeforeExternalGroupBy is the maximum bytes used by a TiFlash hash aggregation before spill to disk
	// Default value is -1, means it will not be pushed down to TiFlash
	// If the value is bigger than -1, it will be pushed down to TiFlash, and if the value is 0, it means
	// not limit and spill will never happen
	TiFlashMaxBytesBeforeExternalGroupBy int64

	// TiFlashMaxBytesBeforeExternalSort is the maximum bytes used by a TiFlash sort/TopN before spill to disk
	// Default value is -1, means it will not be pushed down to TiFlash
	// If the value is bigger than -1, it will be pushed down to TiFlash, and if the value is 0, it means
	// not limit and spill will never happen
	TiFlashMaxBytesBeforeExternalSort int64

	// TiFlash max query memory per node, -1 and 0 means no limit, and the default value is 0
	// If TiFlashMaxQueryMemoryPerNode > 0 && TiFlashQuerySpillRatio > 0, it will trigger auto spill in TiFlash side, and when auto spill
	// is triggered, per executor's memory usage threshold set by TiFlashMaxBytesBeforeExternalJoin/TiFlashMaxBytesBeforeExternalGroupBy/TiFlashMaxBytesBeforeExternalSort will be ignored.
	TiFlashMaxQueryMemoryPerNode int64

	// TiFlashQuerySpillRatio is the percentage threshold to trigger auto spill in TiFlash if TiFlashMaxQueryMemoryPerNode is set
	TiFlashQuerySpillRatio float64

	// TiDBAllowAutoRandExplicitInsert indicates whether explicit insertion on auto_random column is allowed.
	AllowAutoRandExplicitInsert bool

	// BroadcastJoinThresholdSize is used to limit the size of smaller table.
	// It's unit is bytes, if the size of small table is larger than it, we will not use bcj.
	BroadcastJoinThresholdSize int64

	// BroadcastJoinThresholdCount is used to limit the total count of smaller table.
	// If we can't estimate the size of one side of join child, we will check if its row number exceeds this limitation.
	BroadcastJoinThresholdCount int64

	// PreferBCJByExchangeDataSize indicates the method used to choose mpp broadcast join
	// false: choose mpp broadcast join by `BroadcastJoinThresholdSize` and `BroadcastJoinThresholdCount`
	// true: compare data exchange size of join and choose the smallest one
	PreferBCJByExchangeDataSize bool

	// LimitPushDownThreshold determines if push Limit or TopN down to TiKV forcibly.
	LimitPushDownThreshold int64

	// CorrelationThreshold is the guard to enable row count estimation using column order correlation.
	CorrelationThreshold float64

	// EnableCorrelationAdjustment is used to indicate if correlation adjustment is enabled.
	EnableCorrelationAdjustment bool

	// CorrelationExpFactor is used to control the heuristic approach of row count estimation when CorrelationThreshold is not met.
	CorrelationExpFactor int

	// CopTiFlashConcurrencyFactor is the concurrency number of computation in tiflash coprocessor.
	CopTiFlashConcurrencyFactor float64

	// CurrInsertValues is used to record current ValuesExpr's values.
	// See http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_values
	CurrInsertValues chunk.Row

	// In https://github.com/pingcap/tidb/issues/14164, we can see that MySQL can enter the column that is not in the insert's SELECT's output.
	// We store the extra columns in this variable.
	CurrInsertBatchExtraCols [][]types.Datum

	// Per-connection time zones. Each client that connects has its own time zone setting, given by the session time_zone variable.
	// See https://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html
	TimeZone *time.Location

	SQLMode mysql.SQLMode

	// AutoIncrementIncrement and AutoIncrementOffset indicates the autoID's start value and increment.
	AutoIncrementIncrement int

	AutoIncrementOffset int

	// SkipASCIICheck check on input value.
	SkipASCIICheck bool

	// SkipUTF8Check check on input value.
	SkipUTF8Check bool

	// DefaultCollationForUTF8MB4 indicates the default collation of UTF8MB4.
	DefaultCollationForUTF8MB4 string

	// BatchInsert indicates if we should split insert data into multiple batches.
	BatchInsert bool

	// BatchDelete indicates if we should split delete data into multiple batches.
	BatchDelete bool

	// BatchCommit indicates if we should split the transaction into multiple batches.
	BatchCommit bool

	// OptimizerSelectivityLevel defines the level of the selectivity estimation in plan.
	OptimizerSelectivityLevel int

	// OptimizerEnableNewOnlyFullGroupByCheck enables the new only_full_group_by check which is implemented by maintaining functional dependency.
	OptimizerEnableNewOnlyFullGroupByCheck bool

	// EnableOuterJoinWithJoinReorder enables TiDB to involve the outer join into the join reorder.
	EnableOuterJoinReorder bool

	// OptimizerEnableNAAJ enables TiDB to use null-aware anti join.
	OptimizerEnableNAAJ bool

	// EnableCascadesPlanner enables the cascades planner.
	EnableCascadesPlanner bool

	// EnableWindowFunction enables the window function.
	EnableWindowFunction bool

	// EnablePipelinedWindowExec enables executing window functions in a pipelined manner.
	EnablePipelinedWindowExec bool

	// AllowProjectionPushDown enables pushdown projection on TiKV.
	AllowProjectionPushDown bool

	// EnableStrictDoubleTypeCheck enables table field double type check.
	EnableStrictDoubleTypeCheck bool

	// EnableVectorizedExpression  enables the vectorized expression evaluation.
	EnableVectorizedExpression bool

	// DDLReorgPriority is the operation priority of adding indices.
	DDLReorgPriority int

	// EnableAutoIncrementInGenerated is used to control whether to allow auto incremented columns in generated columns.
	EnableAutoIncrementInGenerated bool

	// EnablePointGetCache is used to cache value for point get for read only scenario.
	EnablePointGetCache bool

	// PlacementMode the placement mode we use
	//   strict: Check placement settings strictly in ddl operations
	//   ignore: Ignore all placement settings in ddl operations
	PlacementMode string

	// WaitSplitRegionFinish defines the split region behaviour is sync or async.
	WaitSplitRegionFinish bool

	// WaitSplitRegionTimeout defines the split region timeout.
	WaitSplitRegionTimeout uint64

	// EnableChunkRPC indicates whether the coprocessor request can use chunk API.
	EnableChunkRPC bool

	// ConstraintCheckInPlace indicates whether to check the constraint when the SQL executing.
	ConstraintCheckInPlace bool

	// CommandValue indicates which command current session is doing.
	CommandValue uint32

	// TiDBOptJoinReorderThreshold defines the minimal number of join nodes
	// to use the greedy join reorder algorithm.
	TiDBOptJoinReorderThreshold int

	// SlowQueryFile indicates which slow query log file for SLOW_QUERY table to parse.
	SlowQueryFile string

	// EnableFastAnalyze indicates whether to take fast analyze.
	EnableFastAnalyze bool

	// TxnMode indicates should be pessimistic or optimistic.
	TxnMode string

	// MaxExecutionTime is the timeout for select statement, in milliseconds.
	// If the value is 0, timeouts are not enabled.
	// See https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_max_execution_time
	MaxExecutionTime uint64

	// LoadBindingTimeout is the timeout for loading the bind info.
	LoadBindingTimeout uint64

	// TiKVClientReadTimeout is the timeout for readonly kv request in milliseconds, 0 means using default value
	// See https://github.com/pingcap/tidb/blob/7105505a78fc886c33258caa5813baf197b15247/docs/design/2023-06-30-configurable-kv-timeout.md?plain=1#L14-L15
	TiKVClientReadTimeout uint64

	// SQLKiller is a flag to indicate that this query is killed.
	SQLKiller sqlkiller.SQLKiller

	// ConnectionStatus indicates current connection status.
	ConnectionStatus int32

	// ConnectionInfo indicates current connection info used by current session.
	ConnectionInfo *ConnectionInfo

	// NoopFuncsMode allows OFF/ON/WARN values as 0/1/2.
	NoopFuncsMode int

	// StartTime is the start time of the last query. It's set after the query is parsed and before the query is compiled.
	StartTime time.Time

	// DurationParse is the duration of parsing SQL string to AST of the last query.
	DurationParse time.Duration

	// DurationCompile is the duration of compiling AST to execution plan of the last query.
	DurationCompile time.Duration

	// RewritePhaseInfo records all information about the rewriting phase.
	RewritePhaseInfo

	// DurationOptimization is the duration of optimizing a query.
	DurationOptimization time.Duration

	// DurationWaitTS is the duration of waiting for a snapshot TS
	DurationWaitTS time.Duration

	// PrevStmt is used to store the previous executed statement in the current session.
	PrevStmt *LazyStmtText

	// AllowRemoveAutoInc indicates whether a user can drop the auto_increment column attribute or not.
	AllowRemoveAutoInc bool

	// UsePlanBaselines indicates whether we will use plan baselines to adjust plan.
	UsePlanBaselines bool

	// EvolvePlanBaselines indicates whether we will evolve the plan baselines.
	EvolvePlanBaselines bool

	// EnableExtendedStats indicates whether we enable the extended statistics feature.
	EnableExtendedStats bool

	// ReplicaClosestReadThreshold is the minimum response body size that a cop request should be sent to the closest replica.
	// this variable only take effect when `tidb_follower_read` = 'closest-adaptive'
	ReplicaClosestReadThreshold int64

	// IsolationReadEngines is used to isolation read, tidb only read from the stores whose engine type is in the engines.
	IsolationReadEngines map[kv.StoreType]struct{}

	PlannerSelectBlockAsName atomic.Pointer[[]ast.HintTable]

	// LockWaitTimeout is the duration waiting for pessimistic lock in milliseconds
	LockWaitTimeout int64

	// MetricSchemaStep indicates the step when query metric schema.
	MetricSchemaStep int64

	// CDCWriteSource indicates the following data is written by TiCDC if it is not 0.
	CDCWriteSource uint64

	// MetricSchemaRangeDuration indicates the step when query metric schema.
	MetricSchemaRangeDuration int64

	// Some data of cluster-level memory tables will be retrieved many times in different inspection rules,
	// and the cost of retrieving some data is expensive. We use the `TableSnapshot` to cache those data
	// and obtain them lazily, and provide a consistent view of inspection tables for each inspection rules.
	// All cached snapshots will be released at the end of retrieving
	InspectionTableCache map[string]TableSnapshot

	// RowEncoder is reused in session for encode row data.
	RowEncoder rowcodec.Encoder

	// SequenceState cache all sequence's latest value accessed by lastval() builtins. It's a session scoped
	// variable, and all public methods of SequenceState are currently-safe.
	SequenceState *SequenceState

	// WindowingUseHighPrecision determines whether to compute window operations without loss of precision.
	// see https://dev.mysql.com/doc/refman/8.0/en/window-function-optimization.html for more details.
	WindowingUseHighPrecision bool

	// FoundInPlanCache indicates whether this statement was found in plan cache.
	FoundInPlanCache bool
	// PrevFoundInPlanCache indicates whether the last statement was found in plan cache.
	PrevFoundInPlanCache bool

	// FoundInBinding indicates whether the execution plan is matched with the hints in the binding.
	FoundInBinding bool
	// PrevFoundInBinding indicates whether the last execution plan is matched with the hints in the binding.
	PrevFoundInBinding bool

	// OptimizerUseInvisibleIndexes indicates whether optimizer can use invisible index
	OptimizerUseInvisibleIndexes bool

	// SelectLimit limits the max counts of select statement's output
	SelectLimit uint64

	// EnableClusteredIndex indicates whether to enable clustered index when creating a new table.
	EnableClusteredIndex vardef.ClusteredIndexDefMode

	// EnableParallelApply indicates that whether to use parallel apply.
	EnableParallelApply bool

	// EnableRedactLog indicates that whether redact log. Possible values are 'OFF', 'ON', 'MARKER'.
	EnableRedactLog string

	// ShardAllocateStep indicates the max size of continuous rowid shard in one transaction.
	ShardAllocateStep int64

	// LastTxnInfo keeps track the info of last committed transaction.
	LastTxnInfo string

	// LastQueryInfo keeps track the info of last query.
	LastQueryInfo sessionstates.QueryInfo

	// LastDDLInfo keeps track the info of last DDL.
	LastDDLInfo sessionstates.LastDDLInfo

	// PartitionPruneMode indicates how and when to prune partitions.
	PartitionPruneMode atomic2.String

	// TxnScope indicates the scope of the transactions. It should be `global` or equal to the value of key `zone` in config.Labels.
	TxnScope kv.TxnScopeVar

	// EnabledRateLimitAction indicates whether enabled ratelimit action during coprocessor
	EnabledRateLimitAction bool

	// EnableAsyncCommit indicates whether to enable the async commit feature.
	EnableAsyncCommit bool

	// Enable1PC indicates whether to enable the one-phase commit feature.
	Enable1PC bool

	// GuaranteeLinearizability indicates whether to guarantee linearizability
	GuaranteeLinearizability bool

	// AnalyzeVersion indicates how TiDB collect and use analyzed statistics.
	AnalyzeVersion int

	// DisableHashJoin indicates whether to disable hash join.
	DisableHashJoin bool

	// UseHashJoinV2 indicates whether to use hash join v2.
	UseHashJoinV2 bool

	// EnableHistoricalStats indicates whether to enable historical statistics.
	EnableHistoricalStats bool

	// EnableIndexMergeJoin indicates whether to enable index merge join.
	EnableIndexMergeJoin bool

	// TrackAggregateMemoryUsage indicates whether to track the memory usage of aggregate function.
	TrackAggregateMemoryUsage bool

	// TiDBEnableExchangePartition indicates whether to enable exchange partition
	TiDBEnableExchangePartition bool

	// AllowFallbackToTiKV indicates the engine types whose unavailability triggers fallback to TiKV.
	// Now we only support TiFlash.
	AllowFallbackToTiKV map[kv.StoreType]struct{}

	// CTEMaxRecursionDepth indicates The common table expression (CTE) maximum recursion depth.
	// see https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_cte_max_recursion_depth
	CTEMaxRecursionDepth int

	// The temporary table size threshold, which is different from MySQL. See https://github.com/pingcap/tidb/issues/28691.
	TMPTableSize int64

	// EnableStableResultMode if stabilize query results.
	EnableStableResultMode bool

	// EnablePseudoForOutdatedStats if using pseudo for outdated stats
	EnablePseudoForOutdatedStats bool

	// RegardNULLAsPoint if regard NULL as Point
	RegardNULLAsPoint bool

	// LocalTemporaryTables is *infoschema.LocalTemporaryTables, use interface to avoid circle dependency.
	// It's nil if there is no local temporary table.
	LocalTemporaryTables any

	// TemporaryTableData stores committed kv values for temporary table for current session.
	TemporaryTableData TemporaryTableData

	// MPPStoreFailTTL indicates the duration that protect TiDB from sending task to a new recovered TiFlash.
	MPPStoreFailTTL string

	// ReadStaleness indicates the staleness duration for the following query
	ReadStaleness time.Duration

	// Rng stores the rand_seed1 and rand_seed2 for Rand() function
	Rng *mathutil.MysqlRng

	// EnablePaging indicates whether enable paging in coprocessor requests.
	EnablePaging bool

	// EnableLegacyInstanceScope says if SET SESSION can be used to set an instance
	// scope variable. The default is TRUE.
	EnableLegacyInstanceScope bool

	// ReadConsistency indicates the read consistency requirement.
	ReadConsistency ReadConsistencyLevel

	// StatsLoadSyncWait indicates how long to wait for stats load before timeout.
	StatsLoadSyncWait atomic.Int64

	// EnableParallelHashaggSpill indicates if parallel hash agg could spill.
	EnableParallelHashaggSpill bool

	// SysdateIsNow indicates whether Sysdate is an alias of Now function
	SysdateIsNow bool
	// EnableMutationChecker indicates whether to check data consistency for mutations
	EnableMutationChecker bool
	// AssertionLevel controls how strict the assertions on data mutations should be.
	AssertionLevel AssertionLevel
	// IgnorePreparedCacheCloseStmt controls if ignore the close-stmt command for prepared statement.
	IgnorePreparedCacheCloseStmt bool
	// EnableNewCostInterface is a internal switch to indicates whether to use the new cost calculation interface.
	EnableNewCostInterface bool
	// CostModelVersion is a internal switch to indicates the Cost Model Version.
	CostModelVersion int
	// IndexJoinDoubleReadPenaltyCostRate indicates whether to add some penalty cost to IndexJoin and how much of it.
	IndexJoinDoubleReadPenaltyCostRate float64

	// BatchPendingTiFlashCount shows the threshold of pending TiFlash tables when batch adding.
	BatchPendingTiFlashCount int
	// RcWriteCheckTS indicates whether some special write statements don't get latest tso from PD at RC
	RcWriteCheckTS bool
	// RemoveOrderbyInSubquery indicates whether to remove ORDER BY in subquery.
	RemoveOrderbyInSubquery bool
	// NonTransactionalIgnoreError indicates whether to ignore error in non-transactional statements.
	// When set to false, returns immediately when it meets the first error.
	NonTransactionalIgnoreError bool

	// MaxAllowedPacket indicates the maximum size of a packet for the MySQL protocol.
	MaxAllowedPacket uint64

	// TiFlash related optimization, only for MPP.
	TiFlashFineGrainedShuffleStreamCount int64
	TiFlashFineGrainedShuffleBatchSize   uint64

	// RequestSourceType is the type of inner request.
	RequestSourceType string
	// ExplicitRequestSourceType is the type of origin external request.
	ExplicitRequestSourceType string

	// MemoryDebugModeMinHeapInUse indicated the minimum heapInUse threshold that triggers the memoryDebugMode.
	MemoryDebugModeMinHeapInUse int64
	// MemoryDebugModeAlarmRatio indicated the allowable bias ratio of memory tracking accuracy check.
	// When `(memory trakced by tidb) * (1+MemoryDebugModeAlarmRatio) < actual heapInUse`, an alarm log will be recorded.
	MemoryDebugModeAlarmRatio int64

	// EnableAnalyzeSnapshot indicates whether to read data on snapshot when collecting statistics.
	// When it is false, ANALYZE reads the latest data.
	// When it is true, ANALYZE reads data on the snapshot at the beginning of ANALYZE.
	EnableAnalyzeSnapshot bool

	// DefaultStrMatchSelectivity adjust the estimation strategy for string matching expressions that can't be estimated by building into range.
	// when > 0: it's the selectivity for the expression.
	// when = 0: try to use TopN to evaluate the like expression to estimate the selectivity.
	DefaultStrMatchSelectivity float64

	// TiFlashFastScan indicates whether use fast scan in TiFlash
	TiFlashFastScan bool

	// PrimaryKeyRequired indicates if sql_require_primary_key sysvar is set
	PrimaryKeyRequired bool

	// EnablePreparedPlanCache indicates whether to enable prepared plan cache.
	EnablePreparedPlanCache bool

	// PreparedPlanCacheSize controls the size of prepared plan cache.
	PreparedPlanCacheSize uint64

	// PreparedPlanCacheMonitor indicates whether to enable prepared plan cache monitor.
	EnablePreparedPlanCacheMemoryMonitor bool

	// EnablePlanCacheForParamLimit controls whether the prepare statement with parameterized limit can be cached
	EnablePlanCacheForParamLimit bool

	// EnablePlanCacheForSubquery controls whether the prepare statement with sub query can be cached
	EnablePlanCacheForSubquery bool

	// EnableNonPreparedPlanCache indicates whether to enable non-prepared plan cache.
	EnableNonPreparedPlanCache bool

	// EnableNonPreparedPlanCacheForDML indicates whether to enable non-prepared plan cache for DML statements.
	EnableNonPreparedPlanCacheForDML bool

	// EnableFuzzyBinding indicates whether to enable fuzzy binding.
	EnableFuzzyBinding bool

	// PlanCacheInvalidationOnFreshStats controls if plan cache will be invalidated automatically when
	// related stats are analyzed after the plan cache is generated.
	PlanCacheInvalidationOnFreshStats bool

	// NonPreparedPlanCacheSize controls the size of non-prepared plan cache.
	NonPreparedPlanCacheSize uint64

	// PlanCacheMaxPlanSize controls the maximum size of a plan that can be cached.
	PlanCacheMaxPlanSize uint64

	// SessionPlanCacheSize controls the size of session plan cache.
	SessionPlanCacheSize uint64

	// ConstraintCheckInPlacePessimistic controls whether to skip the locking of some keys in pessimistic transactions.
	// Postpone the conflict check and constraint check to prewrite or later pessimistic locking requests.
	ConstraintCheckInPlacePessimistic bool

	// EnableTiFlashReadForWriteStmt indicates whether to enable TiFlash to read for write statements.
	EnableTiFlashReadForWriteStmt bool

	// EnableUnsafeSubstitute indicates whether to enable generate column takes unsafe substitute.
	EnableUnsafeSubstitute bool

	// ForeignKeyChecks indicates whether to enable foreign key constraint check.
	ForeignKeyChecks bool

	// RangeMaxSize is the max memory limit for ranges. When the optimizer estimates that the memory usage of complete
	// ranges would exceed the limit, it chooses less accurate ranges such as full range. 0 indicates that there is no
	// memory limit for ranges.
	RangeMaxSize int64

	// LastPlanReplayerToken indicates the last plan replayer token
	LastPlanReplayerToken string

	// InPlanReplayer means we are now executing a statement for a PLAN REPLAYER SQL.
	// Note that PLAN REPLAYER CAPTURE is not included here.
	InPlanReplayer bool

	// AnalyzePartitionConcurrency indicates concurrency for partitions in Analyze
	AnalyzePartitionConcurrency int
	// AnalyzePartitionMergeConcurrency indicates concurrency for merging partition stats
	AnalyzePartitionMergeConcurrency int

	// EnableAsyncMergeGlobalStats indicates whether to enable async merge global stats
	EnableAsyncMergeGlobalStats bool

	// EnableExternalTSRead indicates whether to enable read through external ts
	EnableExternalTSRead bool

	HookContext

	// MemTracker indicates the memory tracker of current session.
	MemTracker *memory.Tracker
	// MemDBDBFootprint tracks the memory footprint of memdb, and is attached to `MemTracker`
	MemDBFootprint *memory.Tracker
	DiskTracker    *memory.Tracker

	// OptPrefixIndexSingleScan indicates whether to do some optimizations to avoid double scan for prefix index.
	// When set to true, `col is (not) null`(`col` is index prefix column) is regarded as index filter rather than table filter.
	OptPrefixIndexSingleScan bool

	// EnableReuseChunk indicates  request chunk whether use chunk alloc
	EnableReuseChunk bool

	// EnableAdvancedJoinHint indicates whether the join method hint is compatible with join order hint.
	EnableAdvancedJoinHint bool

	// EnablePlanReplayerCapture indicates whether enabled plan replayer capture
	EnablePlanReplayerCapture bool

	// EnablePlanReplayedContinuesCapture indicates whether enabled plan replayer continues capture
	EnablePlanReplayedContinuesCapture bool

	// PlanReplayerFinishedTaskKey used to record the finished plan replayer task key in order not to record the
	// duplicate task in plan replayer continues capture
	PlanReplayerFinishedTaskKey map[replayer.PlanReplayerTaskKey]struct{}

	// StoreBatchSize indicates the batch size limit of store batch, set this field to 0 to disable store batch.
	StoreBatchSize int

	// Resource group name
	// NOTE: all statement relate operation should use StmtCtx.ResourceGroupName instead.
	// NOTE: please don't change it directly. Use `SetResourceGroupName`, because it'll need to inc/dec the metrics
	ResourceGroupName string

	// PessimisticTransactionFairLocking controls whether fair locking for pessimistic transaction
	// is enabled.
	PessimisticTransactionFairLocking bool

	// EnableINLJoinInnerMultiPattern indicates whether enable multi pattern for index join inner side
	// For now it is not public to user
	EnableINLJoinInnerMultiPattern bool

	// Enable late materialization: push down some selection condition to tablescan.
	EnableLateMaterialization bool

	// EnableRowLevelChecksum indicates whether row level checksum is enabled.
	EnableRowLevelChecksum bool

	// TiFlashComputeDispatchPolicy indicates how to dipatch task to tiflash_compute nodes.
	// Only for disaggregated-tiflash mode.
	TiFlashComputeDispatchPolicy tiflashcompute.DispatchPolicy

	// SlowTxnThreshold is the threshold of slow transaction logs
	SlowTxnThreshold uint64

	// LoadBasedReplicaReadThreshold is the threshold for the estimated wait duration of a store.
	// If exceeding the threshold, try other stores using replica read.
	LoadBasedReplicaReadThreshold time.Duration

	// OptOrderingIdxSelThresh is the threshold for optimizer to consider the ordering index.
	// If there exists an index whose estimated selectivity is smaller than this threshold, the optimizer won't
	// use the ExpectedCnt to adjust the estimated row count for index scan.
	OptOrderingIdxSelThresh float64

	// OptOrderingIdxSelRatio is the ratio for optimizer to determine when qualified rows from filtering outside
	// of the index will be found during the scan of an ordering index.
	// If all filtering is applied as matching on the ordering index, this ratio will have no impact.
	// Value < 0 disables this enhancement.
	// Value 0 will estimate row(s) found immediately.
	// 0 > value <= 1 applies that percentage as the estimate when rows are found. For example 0.1 = 10%.
	OptOrderingIdxSelRatio float64

	// EnableMPPSharedCTEExecution indicates whether we enable the shared CTE execution strategy on MPP side.
	EnableMPPSharedCTEExecution bool

	// OptimizerFixControl control some details of the optimizer behavior through the tidb_opt_fix_control variable.
	OptimizerFixControl map[uint64]string

	// FastCheckTable is used to control whether fast check table is enabled.
	FastCheckTable bool

	// HypoIndexes are for the Index Advisor.
	HypoIndexes map[string]map[string]map[string]*model.IndexInfo // dbName -> tblName -> idxName -> idxInfo

	// TiFlashReplicaRead indicates the policy of TiFlash node selection when the query needs the TiFlash engine.
	TiFlashReplicaRead tiflash.ReplicaRead

	// HypoTiFlashReplicas are for the Index Advisor.
	HypoTiFlashReplicas map[string]map[string]struct{} // dbName -> tblName -> whether to have replicas

	// Whether to lock duplicate keys in INSERT IGNORE and REPLACE statements,
	// or unchanged unique keys in UPDATE statements, see PR #42210 and #42713
	LockUnchangedKeys bool

	// AnalyzeSkipColumnTypes indicates the column types whose statistics would not be collected when executing the ANALYZE command.
	AnalyzeSkipColumnTypes map[string]struct{}

	// SkipMissingPartitionStats controls how to handle missing partition stats when merging partition stats to global stats.
	// When set to true, skip missing partition stats and continue to merge other partition stats to global stats.
	// When set to false, give up merging partition stats to global stats.
	SkipMissingPartitionStats bool

	// SessionAlias is the identifier of the session
	SessionAlias string

	// OptObjective indicates whether the optimizer should be more stable, predictable or more aggressive.
	// For now, the possible values and corresponding behaviors are:
	// OptObjectiveModerate: The default value. The optimizer considers the real-time stats (real-time row count, modify count).
	// OptObjectiveDeterminate: The optimizer doesn't consider the real-time stats.
	OptObjective string

	CompressionAlgorithm int
	CompressionLevel     int

	// TxnEntrySizeLimit indicates indicates the max size of a entry in membuf. The default limit (from config) will be
	// overwritten if this value is not 0.
	TxnEntrySizeLimit uint64

	// DivPrecisionIncrement indicates the number of digits by which to increase the scale of the result
	// of division operations performed with the / operator.
	DivPrecisionIncrement int

	// allowed when tikv disk full happened.
	DiskFullOpt kvrpcpb.DiskFullOpt

	// GroupConcatMaxLen represents the maximum length of the result of GROUP_CONCAT.
	GroupConcatMaxLen uint64

	// TiFlashPreAggMode indicates the policy of pre aggregation.
	TiFlashPreAggMode string

	// EnableLazyCursorFetch defines whether to enable the lazy cursor fetch.
	EnableLazyCursorFetch bool

	// SharedLockPromotion indicates whether the `select for lock` statements would be executed as the
	// `select for update` statements which do acquire pessimsitic locks.
	SharedLockPromotion bool

	// ScatterRegion will scatter the regions for DDLs when it is "table" or "global", "" indicates not trigger scatter.
	ScatterRegion string

	// CacheStmtExecInfo is a cache for the statement execution information, used to reduce the overhead of memory allocation.
	CacheStmtExecInfo *stmtsummary.StmtExecInfo
	// contains filtered or unexported fields
}

SessionVars is to handle user-defined or global variables in the current session.

func NewSessionVars

func NewSessionVars(hctx HookContext) *SessionVars

NewSessionVars creates a session vars object.

func (*SessionVars) AddNonPreparedPlanCacheStmt

func (s *SessionVars) AddNonPreparedPlanCacheStmt(sql string, stmt any)

AddNonPreparedPlanCacheStmt adds this PlanCacheStmt into non-preapred plan-cache stmt cache

func (*SessionVars) AddPlanReplayerFinishedTaskKey

func (s *SessionVars) AddPlanReplayerFinishedTaskKey(key replayer.PlanReplayerTaskKey)

AddPlanReplayerFinishedTaskKey record finished task key in session

func (*SessionVars) AddPreparedStmt

func (s *SessionVars) AddPreparedStmt(stmtID uint32, stmt any) error

AddPreparedStmt adds prepareStmt to current session and count in global.

func (*SessionVars) AllocNewPlanID

func (s *SessionVars) AllocNewPlanID() int

AllocNewPlanID alloc new ID

func (*SessionVars) AllocPlanColumnID

func (s *SessionVars) AllocPlanColumnID() int64

AllocPlanColumnID allocates column id for plan.

func (*SessionVars) BuildParserConfig

func (s *SessionVars) BuildParserConfig() parser.ParserConfig

BuildParserConfig generate parser.ParserConfig for initial parser

func (*SessionVars) CheckAndGetTxnScope

func (s *SessionVars) CheckAndGetTxnScope() string

CheckAndGetTxnScope will return the transaction scope we should use in the current session.

func (*SessionVars) CheckPlanReplayerFinishedTaskKey

func (s *SessionVars) CheckPlanReplayerFinishedTaskKey(key replayer.PlanReplayerTaskKey) bool

CheckPlanReplayerFinishedTaskKey check whether the key exists

func (*SessionVars) ChooseMppExchangeCompressionMode

func (s *SessionVars) ChooseMppExchangeCompressionMode() vardef.ExchangeCompressionMode

ChooseMppExchangeCompressionMode indicates the data compression method in mpp exchange operator

func (*SessionVars) ChooseMppVersion

func (s *SessionVars) ChooseMppVersion() kv.MppVersion

ChooseMppVersion indicates the mpp-version used to build mpp plan, if mpp-version is unspecified, use the latest version.

func (*SessionVars) CleanBuffers

func (s *SessionVars) CleanBuffers()

CleanBuffers cleans the temporary bufs

func (*SessionVars) CleanupTxnReadTSIfUsed

func (s *SessionVars) CleanupTxnReadTSIfUsed()

CleanupTxnReadTSIfUsed cleans txnReadTS if used

func (*SessionVars) ClearAlloc

func (s *SessionVars) ClearAlloc(alloc *chunk.Allocator, hasErr bool)

ClearAlloc indicates stop reuse chunk. If `hasErr` is true, it'll also recreate the `alloc` in parameter.

func (*SessionVars) ClearDiskFullOpt

func (s *SessionVars) ClearDiskFullOpt()

ClearDiskFullOpt resets the session variable DiskFullOpt to DiskFullOpt_NotAllowedOnFull.

func (*SessionVars) ClearRelatedTableForMDL

func (s *SessionVars) ClearRelatedTableForMDL()

ClearRelatedTableForMDL clears the related table for MDL. related tables for MDL is filled during build logical plan or Preprocess for all DataSources, even for queries inside DDLs like `create view as select xxx` and `create table as select xxx`. it should be cleared before we execute the DDL statement.

func (*SessionVars) DecodeSessionStates

func (s *SessionVars) DecodeSessionStates(_ context.Context, sessionStates *sessionstates.SessionStates) (err error)

DecodeSessionStates restores session states from SessionStates.

func (*SessionVars) EnableEvalTopNEstimationForStrMatch

func (s *SessionVars) EnableEvalTopNEstimationForStrMatch() bool

EnableEvalTopNEstimationForStrMatch means if we need to evaluate expression with TopN to improve estimation. Currently, it's only for string matching functions (like and regexp).

func (*SessionVars) EnableForceInlineCTE

func (s *SessionVars) EnableForceInlineCTE() bool

EnableForceInlineCTE returns the session variable enableForceInlineCTE

func (*SessionVars) EncodeSessionStates

func (s *SessionVars) EncodeSessionStates(_ context.Context, sessionStates *sessionstates.SessionStates) (err error)

EncodeSessionStates saves session states into SessionStates.

func (*SessionVars) ExchangeChunkStatus

func (s *SessionVars) ExchangeChunkStatus()

ExchangeChunkStatus give the status to preUseChunkAlloc

func (*SessionVars) GetAllowInSubqToJoinAndAgg

func (s *SessionVars) GetAllowInSubqToJoinAndAgg() bool

GetAllowInSubqToJoinAndAgg get AllowInSubqToJoinAndAgg from sql hints and SessionVars.allowInSubqToJoinAndAgg.

func (*SessionVars) GetAllowPreferRangeScan

func (s *SessionVars) GetAllowPreferRangeScan() bool

GetAllowPreferRangeScan get preferRangeScan from SessionVars.preferRangeScan.

func (*SessionVars) GetCPUFactor

func (s *SessionVars) GetCPUFactor() float64

GetCPUFactor returns the session variable cpuFactor

func (*SessionVars) GetCharsetInfo

func (s *SessionVars) GetCharsetInfo() (charset, collation string)

GetCharsetInfo gets charset and collation for current context. What character set should the server translate a statement to after receiving it? For this, the server uses the character_set_connection and collation_connection system variables. It converts statements sent by the client from character_set_client to character_set_connection (except for string literals that have an introducer such as _latin1 or _utf8). collation_connection is important for comparisons of literal strings. For comparisons of strings with column values, collation_connection does not matter because columns have their own collation, which has a higher collation precedence. See https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html

func (*SessionVars) GetChunkAllocator

func (s *SessionVars) GetChunkAllocator() chunk.Allocator

GetChunkAllocator returns a valid chunk allocator.

func (*SessionVars) GetConcurrencyFactor

func (s *SessionVars) GetConcurrencyFactor() float64

GetConcurrencyFactor returns the session variable concurrencyFactor

func (*SessionVars) GetCopCPUFactor

func (s *SessionVars) GetCopCPUFactor() float64

GetCopCPUFactor returns the session variable copCPUFactor

func (*SessionVars) GetDescScanFactor

func (s *SessionVars) GetDescScanFactor(tbl *model.TableInfo) float64

GetDescScanFactor returns the session variable descScanFactor returns 0 when tbl is a temporary table.

func (*SessionVars) GetDiskFactor

func (s *SessionVars) GetDiskFactor() float64

GetDiskFactor returns the session variable diskFactor

func (*SessionVars) GetDiskFullOpt

func (s *SessionVars) GetDiskFullOpt() kvrpcpb.DiskFullOpt

GetDiskFullOpt returns the value of DiskFullOpt in the current session.

func (*SessionVars) GetDivPrecisionIncrement

func (s *SessionVars) GetDivPrecisionIncrement() int

GetDivPrecisionIncrement returns the specified value of DivPrecisionIncrement.

func (*SessionVars) GetEnableCascadesPlanner

func (s *SessionVars) GetEnableCascadesPlanner() bool

GetEnableCascadesPlanner get EnableCascadesPlanner from sql hints and SessionVars.EnableCascadesPlanner.

func (*SessionVars) GetEnableIndexMerge

func (s *SessionVars) GetEnableIndexMerge() bool

GetEnableIndexMerge get EnableIndexMerge from SessionVars.enableIndexMerge.

func (*SessionVars) GetEnablePseudoForOutdatedStats

func (s *SessionVars) GetEnablePseudoForOutdatedStats() bool

GetEnablePseudoForOutdatedStats get EnablePseudoForOutdatedStats from SessionVars.EnablePseudoForOutdatedStats.

func (*SessionVars) GetExecuteDuration

func (s *SessionVars) GetExecuteDuration() time.Duration

GetExecuteDuration returns the execute duration of the last statement in the current session.

func (*SessionVars) GetGlobalSystemVar

func (s *SessionVars) GetGlobalSystemVar(ctx context.Context, name string) (string, error)

GetGlobalSystemVar gets a global system variable.

func (*SessionVars) GetIsolationReadEngines

func (s *SessionVars) GetIsolationReadEngines() map[kv.StoreType]struct{}

GetIsolationReadEngines gets isolation read engines.

func (*SessionVars) GetMaxExecutionTime

func (s *SessionVars) GetMaxExecutionTime() uint64

GetMaxExecutionTime get the max execution timeout value.

func (*SessionVars) GetMemoryFactor

func (s *SessionVars) GetMemoryFactor() float64

GetMemoryFactor returns the session variable memoryFactor

func (*SessionVars) GetNegateStrMatchDefaultSelectivity

func (s *SessionVars) GetNegateStrMatchDefaultSelectivity() float64

GetNegateStrMatchDefaultSelectivity means the default selectivity for not like and not regexp. Note:

  0 is a special value, which means the default selectivity is 0.9 and TopN assisted estimation is enabled.
  0.8 (the default value) is also a special value. For backward compatibility, when the variable is set to 0.8, we
keep the default selectivity of like/regexp and not like/regexp all 0.8.

func (*SessionVars) GetNetworkFactor

func (s *SessionVars) GetNetworkFactor(tbl *model.TableInfo) float64

GetNetworkFactor returns the session variable networkFactor returns 0 when tbl is a temporary table.

func (*SessionVars) GetNextPreparedStmtID

func (s *SessionVars) GetNextPreparedStmtID() uint32

GetNextPreparedStmtID generates and returns the next session scope prepared statement id.

func (*SessionVars) GetNonPreparedPlanCacheStmt

func (s *SessionVars) GetNonPreparedPlanCacheStmt(sql string) any

GetNonPreparedPlanCacheStmt gets the PlanCacheStmt.

func (*SessionVars) GetOptObjective

func (s *SessionVars) GetOptObjective() string

GetOptObjective return the session variable "tidb_opt_objective". Please see comments of SessionVars.OptObjective for details.

func (*SessionVars) GetOptimizerFixControlMap

func (s *SessionVars) GetOptimizerFixControlMap() map[uint64]string

GetOptimizerFixControlMap returns the specified value of the optimizer fix control.

func (*SessionVars) GetParseParams

func (s *SessionVars) GetParseParams() []parser.ParseParam

GetParseParams gets the parse parameters from session variables.

func (*SessionVars) GetPreparedStmtByID

func (s *SessionVars) GetPreparedStmtByID(stmtID uint32) (any, error)

GetPreparedStmtByID returns the prepared statement specified by stmtID.

func (*SessionVars) GetPreparedStmtByName

func (s *SessionVars) GetPreparedStmtByName(stmtName string) (any, error)

GetPreparedStmtByName returns the prepared statement specified by stmtName.

func (*SessionVars) GetPrevStmtDigest

func (s *SessionVars) GetPrevStmtDigest() string

GetPrevStmtDigest returns the digest of the previous statement.

func (*SessionVars) GetReadableTxnMode

func (s *SessionVars) GetReadableTxnMode() string

GetReadableTxnMode returns the session variable TxnMode but rewrites it to "OPTIMISTIC" when it's empty.

func (*SessionVars) GetRelatedTableForMDL

func (s *SessionVars) GetRelatedTableForMDL() *sync.Map

GetRelatedTableForMDL gets the related table for metadata lock.

func (*SessionVars) GetReplicaRead

func (s *SessionVars) GetReplicaRead() kv.ReplicaReadType

GetReplicaRead get ReplicaRead from sql hints and SessionVars.replicaRead.

func (*SessionVars) GetRowIDShardGenerator

func (s *SessionVars) GetRowIDShardGenerator() *RowIDShardGenerator

GetRowIDShardGenerator shard row id generator

func (*SessionVars) GetRuntimeFilterMode

func (s *SessionVars) GetRuntimeFilterMode() RuntimeFilterMode

GetRuntimeFilterMode return the session variable runtimeFilterMode

func (*SessionVars) GetRuntimeFilterTypes

func (s *SessionVars) GetRuntimeFilterTypes() []RuntimeFilterType

GetRuntimeFilterTypes return the session variable runtimeFilterTypes

func (*SessionVars) GetScanFactor

func (s *SessionVars) GetScanFactor(tbl *model.TableInfo) float64

GetScanFactor returns the session variable scanFactor returns 0 when tbl is a temporary table.

func (*SessionVars) GetSeekFactor

func (s *SessionVars) GetSeekFactor(tbl *model.TableInfo) float64

GetSeekFactor returns the session variable seekFactor returns 0 when tbl is a temporary table.

func (*SessionVars) GetSessionOrGlobalSystemVar

func (s *SessionVars) GetSessionOrGlobalSystemVar(ctx context.Context, name string) (string, error)

GetSessionOrGlobalSystemVar gets a system variable. If it is a session only variable, use the default value defined in code. Returns error if there is no such variable.

func (*SessionVars) GetSessionStatesSystemVar

func (s *SessionVars) GetSessionStatesSystemVar(name string) (string, bool, error)

GetSessionStatesSystemVar gets the session variable value for session states. It's only used for encoding session states when migrating a session. The returned boolean indicates whether to keep this value in the session states.

func (*SessionVars) GetSessionVars

func (s *SessionVars) GetSessionVars() *SessionVars

GetSessionVars implements the `SessionVarsProvider` interface.

func (*SessionVars) GetSplitRegionTimeout

func (s *SessionVars) GetSplitRegionTimeout() time.Duration

GetSplitRegionTimeout gets split region timeout.

func (*SessionVars) GetStrMatchDefaultSelectivity

func (s *SessionVars) GetStrMatchDefaultSelectivity() float64

GetStrMatchDefaultSelectivity means the default selectivity for like and regexp. Note: 0 is a special value, which means the default selectivity is 0.1 and TopN assisted estimation is enabled.

func (*SessionVars) GetSystemVar

func (s *SessionVars) GetSystemVar(name string) (string, bool)

GetSystemVar gets the string value of a system variable.

func (*SessionVars) GetTemporaryTable

func (s *SessionVars) GetTemporaryTable(tblInfo *model.TableInfo) tableutil.TempTable

GetTemporaryTable returns a TempTable by tableInfo.

func (*SessionVars) GetTiKVClientReadTimeout

func (s *SessionVars) GetTiKVClientReadTimeout() uint64

GetTiKVClientReadTimeout returns readonly kv request timeout, prefer query hint over session variable

func (*SessionVars) GetTotalCostDuration

func (s *SessionVars) GetTotalCostDuration() time.Duration

GetTotalCostDuration returns the total cost duration of the last statement in the current session.

func (*SessionVars) GetUseChunkAlloc

func (s *SessionVars) GetUseChunkAlloc() bool

GetUseChunkAlloc return useChunkAlloc status

func (*SessionVars) GetWriteStmtBufs

func (s *SessionVars) GetWriteStmtBufs() *WriteStmtBufs

GetWriteStmtBufs get pointer of SessionVars.writeStmtBufs.

func (*SessionVars) HasStatusFlag

func (s *SessionVars) HasStatusFlag(flag uint16) bool

HasStatusFlag gets the session server status variable, returns true if it is on.

func (*SessionVars) InTxn

func (s *SessionVars) InTxn() bool

InTxn returns if the session is in transaction.

func (*SessionVars) InitStatementContext

func (s *SessionVars) InitStatementContext() *stmtctx.StatementContext

InitStatementContext initializes a StatementContext, the object is reused to reduce allocation.

func (*SessionVars) IsAllocValid

func (s *SessionVars) IsAllocValid() bool

IsAllocValid check if chunk reuse is enable or chunkPool is inused.

func (*SessionVars) IsAutocommit

func (s *SessionVars) IsAutocommit() bool

IsAutocommit returns if the session is set to autocommit.

func (*SessionVars) IsDynamicPartitionPruneEnabled

func (s *SessionVars) IsDynamicPartitionPruneEnabled() bool

IsDynamicPartitionPruneEnabled indicates whether dynamic partition prune enabled Note that: IsDynamicPartitionPruneEnabled only indicates whether dynamic partition prune mode is enabled according to session variable, it isn't guaranteed to be used during query due to other conditions checking.

func (*SessionVars) IsIsolation

func (s *SessionVars) IsIsolation(isolation string) bool

IsIsolation if true it means the transaction is at that isolation level.

func (*SessionVars) IsMPPAllowed

func (s *SessionVars) IsMPPAllowed() bool

IsMPPAllowed returns whether mpp execution is allowed.

func (*SessionVars) IsMPPEnforced

func (s *SessionVars) IsMPPEnforced() bool

IsMPPEnforced returns whether mpp execution is enforced.

func (*SessionVars) IsPessimisticReadConsistency

func (s *SessionVars) IsPessimisticReadConsistency() bool

IsPessimisticReadConsistency if true it means the statement is in a read consistency pessimistic transaction.

func (*SessionVars) IsPlanReplayerCaptureEnabled

func (s *SessionVars) IsPlanReplayerCaptureEnabled() bool

IsPlanReplayerCaptureEnabled indicates whether capture or continues capture enabled

func (*SessionVars) IsReplicaReadClosestAdaptive

func (s *SessionVars) IsReplicaReadClosestAdaptive() bool

IsReplicaReadClosestAdaptive returns whether adaptive closest replica can be enabled.

func (*SessionVars) IsRowLevelChecksumEnabled

func (s *SessionVars) IsRowLevelChecksumEnabled() bool

IsRowLevelChecksumEnabled indicates whether row level checksum is enabled for current session, that is tidb_enable_row_level_checksum is on and tidb_row_format_version is 2 and it's not a internal session.

func (*SessionVars) IsRuntimeFilterEnabled

func (s *SessionVars) IsRuntimeFilterEnabled() bool

IsRuntimeFilterEnabled return runtime filter mode whether OFF

func (*SessionVars) IsTiFlashCopBanned

func (s *SessionVars) IsTiFlashCopBanned() bool

IsTiFlashCopBanned returns whether cop execution is allowed.

func (*SessionVars) IsolationLevelForNewTxn

func (s *SessionVars) IsolationLevelForNewTxn() (isolation string)

IsolationLevelForNewTxn returns the isolation level if we want to enter a new transaction

func (*SessionVars) Location

func (s *SessionVars) Location() *time.Location

Location returns the value of time_zone session variable. If it is nil, then return time.Local.

func (*SessionVars) PessimisticLockEligible

func (s *SessionVars) PessimisticLockEligible() bool

PessimisticLockEligible indicates whether pessimistic lock should not be ignored for the current statement execution. There are cases the `for update` clause should not take effect, like autocommit statements with “pessimistic-auto-commit disabled.

func (*SessionVars) RaiseWarningWhenMPPEnforced

func (s *SessionVars) RaiseWarningWhenMPPEnforced(warning string)

RaiseWarningWhenMPPEnforced will raise a warning when mpp mode is enforced and executing explain statement. TODO: Confirm whether this function will be inlined and omit the overhead of string construction when calling with false condition.

func (*SessionVars) RegisterScalarSubQ

func (s *SessionVars) RegisterScalarSubQ(scalarSubQ any)

RegisterScalarSubQ register a scalar sub query into the map. This will be used for EXPLAIN.

func (*SessionVars) RemovePreparedStmt

func (s *SessionVars) RemovePreparedStmt(stmtID uint32)

RemovePreparedStmt removes preparedStmt from current session and decrease count in global.

func (*SessionVars) SetAlloc

func (s *SessionVars) SetAlloc(alloc chunk.Allocator)

SetAlloc Attempt to set the buffer pool address

func (*SessionVars) SetAllowInSubqToJoinAndAgg

func (s *SessionVars) SetAllowInSubqToJoinAndAgg(val bool)

SetAllowInSubqToJoinAndAgg set SessionVars.allowInSubqToJoinAndAgg.

func (*SessionVars) SetAllowPreferRangeScan

func (s *SessionVars) SetAllowPreferRangeScan(val bool)

SetAllowPreferRangeScan set SessionVars.preferRangeScan.

func (*SessionVars) SetDiskFullOpt

func (s *SessionVars) SetDiskFullOpt(level kvrpcpb.DiskFullOpt)

SetDiskFullOpt sets the session variable DiskFullOpt

func (*SessionVars) SetEnableCascadesPlanner

func (s *SessionVars) SetEnableCascadesPlanner(val bool)

SetEnableCascadesPlanner set SessionVars.EnableCascadesPlanner.

func (*SessionVars) SetEnableIndexMerge

func (s *SessionVars) SetEnableIndexMerge(val bool)

SetEnableIndexMerge set SessionVars.enableIndexMerge.

func (*SessionVars) SetEnablePseudoForOutdatedStats

func (s *SessionVars) SetEnablePseudoForOutdatedStats(val bool)

SetEnablePseudoForOutdatedStats set SessionVars.EnablePseudoForOutdatedStats.

func (*SessionVars) SetInTxn

func (s *SessionVars) SetInTxn(val bool)

SetInTxn sets whether the session is in transaction. It also updates the IsExplicit flag in TxnCtx if val is true.

func (*SessionVars) SetLastInsertID

func (s *SessionVars) SetLastInsertID(insertID uint64)

SetLastInsertID saves the last insert id to the session context. TODO: we may store the result for last_insert_id sys var later.

func (*SessionVars) SetNextPreparedStmtID

func (s *SessionVars) SetNextPreparedStmtID(preparedStmtID uint32)

SetNextPreparedStmtID sets the next prepared statement id. It's only used in restoring session states.

func (*SessionVars) SetPrevStmtDigest

func (s *SessionVars) SetPrevStmtDigest(prevStmtDigest string)

SetPrevStmtDigest sets the digest of the previous statement.

func (*SessionVars) SetReplicaRead

func (s *SessionVars) SetReplicaRead(val kv.ReplicaReadType)

SetReplicaRead set SessionVars.replicaRead.

func (*SessionVars) SetResourceGroupName

func (s *SessionVars) SetResourceGroupName(groupName string)

SetResourceGroupName changes the resource group name and inc/dec the metrics accordingly.

func (*SessionVars) SetStatusFlag

func (s *SessionVars) SetStatusFlag(flag uint16, on bool)

SetStatusFlag sets the session server status variable. If on is true sets the flag in session status, otherwise removes the flag.

func (*SessionVars) SetStringUserVar

func (s *SessionVars) SetStringUserVar(name string, strVal string, collation string)

SetStringUserVar set the value and collation for user defined variable.

func (*SessionVars) SetSystemVar

func (s *SessionVars) SetSystemVar(name string, val string) error

SetSystemVar sets the value of a system variable for session scope. Values are automatically normalized (i.e. oN / on / 1 => ON) and the validation function is run. To set with less validation, see SetSystemVarWithRelaxedValidation.

func (*SessionVars) SetSystemVarWithOldValAsRet

func (s *SessionVars) SetSystemVarWithOldValAsRet(name string, val string) (string, error)

SetSystemVarWithOldValAsRet is wrapper of SetSystemVar. Return the old value for later use.

func (*SessionVars) SetSystemVarWithRelaxedValidation

func (s *SessionVars) SetSystemVarWithRelaxedValidation(name string, val string) error

SetSystemVarWithRelaxedValidation sets the value of a system variable for session scope. Validation functions are called, but scope validation is skipped. Errors are not expected to be returned because this could cause upgrade issues.

func (*SessionVars) SetSystemVarWithoutValidation

func (s *SessionVars) SetSystemVarWithoutValidation(name string, val string) error

SetSystemVarWithoutValidation sets the value of a system variable for session scope. Deprecated: Values are NOT normalized or Validated.

func (*SessionVars) SetTxnIsolationLevelOneShotStateForNextTxn

func (s *SessionVars) SetTxnIsolationLevelOneShotStateForNextTxn()

SetTxnIsolationLevelOneShotStateForNextTxn sets the txnIsolationLevelOneShot.state for next transaction.

func (*SessionVars) SlowLogFormat

func (s *SessionVars) SlowLogFormat(logItems *SlowQueryLogItems) string

SlowLogFormat uses for formatting slow log. The slow log output is like below: # Time: 2019-04-28T15:24:04.309074+08:00 # Txn_start_ts: 406315658548871171 # Keyspace_name: keyspace_a # Keyspace_ID: 1 # User@Host: root[root] @ localhost [127.0.0.1] # Conn_ID: 6 # Query_time: 4.895492 # Process_time: 0.161 Request_count: 1 Total_keys: 100001 Processed_keys: 100000 # DB: test # Index_names: [t1.idx1,t2.idx2] # Is_internal: false # Digest: 42a1c8aae6f133e934d4bf0147491709a8812ea05ff8819ec522780fe657b772 # Stats: t1:1,t2:2 # Num_cop_tasks: 10 # Cop_process: Avg_time: 1s P90_time: 2s Max_time: 3s Max_addr: 10.6.131.78 # Cop_wait: Avg_time: 10ms P90_time: 20ms Max_time: 30ms Max_Addr: 10.6.131.79 # Memory_max: 4096 # Disk_max: 65535 # Succ: true # Prev_stmt: begin; select * from t_slim;

func (*SessionVars) Status

func (s *SessionVars) Status() uint16

Status returns the server status.

func (*SessionVars) UseLowResolutionTSO

func (s *SessionVars) UseLowResolutionTSO() bool

UseLowResolutionTSO indicates whether low resolution tso could be used for execution. After `tidb_low_resolution_tso` supports the global scope, this variable is expected to only affect user sessions and not impact internal background sessions and tasks. Currently, one of the problems is that the determination of whether a session is an internal task session within TiDB is quite inconsistent and chaotic, posing risks. Some internal sessions rely on upper-level users correctly using `ExecuteInternal` or `ExecuteRestrictedSQL` for assurance. Additionally, the BR code also contains some session-related encapsulation and usage.

TODO: There needs to be a more comprehensive and unified entry point to ensure that all internal sessions and global user sessions/variables are isolated and do not affect each other.

func (*SessionVars) WithdrawAllPreparedStmt

func (s *SessionVars) WithdrawAllPreparedStmt()

WithdrawAllPreparedStmt remove all preparedStmt in current session and decrease count in global.

type SessionVarsProvider

type SessionVarsProvider interface {
	GetSessionVars() *SessionVars
}

SessionVarsProvider provides the session variables.

type SlowQueryLogItems

type SlowQueryLogItems struct {
	TxnTS             uint64
	KeyspaceName      string
	KeyspaceID        uint32
	SQL               string
	Digest            string
	TimeTotal         time.Duration
	TimeParse         time.Duration
	TimeCompile       time.Duration
	TimeOptimize      time.Duration
	TimeWaitTS        time.Duration
	IndexNames        string
	CopTasks          *execdetails.CopTasksDetails
	ExecDetail        execdetails.ExecDetails
	MemMax            int64
	DiskMax           int64
	Succ              bool
	Prepared          bool
	PlanFromCache     bool
	PlanFromBinding   bool
	HasMoreResults    bool
	PrevStmt          string
	Plan              string
	PlanDigest        string
	BinaryPlan        string
	RewriteInfo       RewritePhaseInfo
	KVExecDetail      *util.ExecDetails
	WriteSQLRespTotal time.Duration
	ExecRetryCount    uint
	ExecRetryTime     time.Duration
	ResultRows        int64
	IsExplicitTxn     bool
	IsWriteCacheTable bool
	UsedStats         *stmtctx.UsedStatsInfo
	IsSyncStatsFailed bool
	Warnings          []JSONSQLWarnForSlowLog
	ResourceGroupName string
	RRU               float64
	WRU               float64
	WaitRUDuration    time.Duration
	CPUUsages         ppcpuusage.CPUUsages
}

SlowQueryLogItems is a collection of items that should be included in the slow query log.

type Statistics

type Statistics interface {
	// GetScope gets the status variables scope.
	GetScope(status string) vardef.ScopeFlag
	// Stats returns the statistics status variables.
	Stats(*SessionVars) (map[string]any, error)
}

Statistics is the interface of statistics.

type StatusVal

type StatusVal struct {
	Scope vardef.ScopeFlag
	Value any
}

StatusVal is the value of the corresponding status variable.

type SysVar

type SysVar struct {
	// Scope is for whether can be changed or not
	Scope vardef.ScopeFlag
	// Name is the variable name.
	Name string
	// Value is the variable value.
	Value string
	// Type is the MySQL type (optional)
	Type vardef.TypeFlag
	// MinValue will automatically be validated when specified (optional)
	MinValue int64
	// MaxValue will automatically be validated when specified (optional)
	MaxValue uint64
	// AutoConvertNegativeBool applies to boolean types (optional)
	AutoConvertNegativeBool bool
	// ReadOnly applies to all types
	ReadOnly bool
	// PossibleValues applies to ENUM type
	PossibleValues []string
	// AllowEmpty is a special TiDB behavior which means "read value from config" (do not use)
	AllowEmpty bool
	// AllowEmptyAll is a special behavior that only applies to TiDBCapturePlanBaseline, TiDBTxnMode (do not use)
	AllowEmptyAll bool
	// AllowAutoValue means that the special value "-1" is permitted, even when outside of range.
	AllowAutoValue bool
	// Validation is a callback after the type validation has been performed, but before the Set function
	Validation func(*SessionVars, string, string, vardef.ScopeFlag) (string, error)
	// SetSession is called after validation but before updating systems[]. It also doubles as an Init function
	// and will be called on all variables in builtinGlobalVariable, regardless of their scope.
	SetSession func(*SessionVars, string) error
	// SetGlobal is called after validation
	SetGlobal func(context.Context, *SessionVars, string) error
	// IsHintUpdatableVerified indicate whether we've confirmed that SET_VAR() hint is worked for this hint.
	IsHintUpdatableVerified bool
	// Deprecated: Hidden previously meant that the variable still responds to SET but doesn't show up in SHOW VARIABLES
	// However, this feature is no longer used. All variables are visible.
	Hidden bool
	// Aliases is a list of sysvars that should also be updated when this sysvar is updated.
	// Updating aliases calls the SET function of the aliases, but does not update their aliases (preventing SET recursion)
	Aliases []string
	// GetSession is a getter function for session scope.
	// It can be used by instance-scoped variables to overwrite the previously expected value.
	GetSession func(*SessionVars) (string, error)
	// GetGlobal is a getter function for global scope.
	GetGlobal func(context.Context, *SessionVars) (string, error)
	// GetStateValue gets the value for session states, which is used for migrating sessions.
	// We need a function to override GetSession sometimes, because GetSession may not return the real value.
	GetStateValue func(*SessionVars) (string, bool, error)
	// Depended indicates whether other variables depend on this one. That is, if this one is not correctly set,
	// another variable cannot be set either.
	// This flag is used to decide the order to replay session variables.
	Depended bool

	// IsNoop defines if the sysvar is a noop included for MySQL compatibility
	IsNoop bool
	// GlobalConfigName is the global config name of this global variable.
	// If the global variable has the global config name,
	// it should store the global config into PD(etcd) too when set global variable.
	GlobalConfigName string
	// RequireDynamicPrivileges is a function to return a dynamic privilege list to check the set sysvar privilege
	RequireDynamicPrivileges func(isGlobal bool, sem bool) []string
	// contains filtered or unexported fields
}

SysVar is for system variable. All the fields of SysVar should be READ ONLY after created.

func GetSysVar

func GetSysVar(name string) *SysVar

GetSysVar returns sys var info for name as key.

func (*SysVar) GetGlobalFromHook

func (sv *SysVar) GetGlobalFromHook(ctx context.Context, s *SessionVars) (string, error)

GetGlobalFromHook calls the GetSession func if it exists.

func (*SysVar) GetNativeValType

func (sv *SysVar) GetNativeValType(val string) (types.Datum, byte, uint)

GetNativeValType attempts to convert the val to the approx MySQL non-string type TODO: only return 3 types now, support others like DOUBLE, TIME later

func (*SysVar) GetSessionFromHook

func (sv *SysVar) GetSessionFromHook(s *SessionVars) (string, error)

GetSessionFromHook calls the GetSession func if it exists.

func (*SysVar) HasGlobalScope

func (sv *SysVar) HasGlobalScope() bool

HasGlobalScope returns true if the scope for the sysVar includes global.

func (*SysVar) HasInstanceScope

func (sv *SysVar) HasInstanceScope() bool

HasInstanceScope returns true if the scope for the sysVar includes instance

func (*SysVar) HasNoneScope

func (sv *SysVar) HasNoneScope() bool

HasNoneScope returns true if the scope for the sysVar is None.

func (*SysVar) HasSessionScope

func (sv *SysVar) HasSessionScope() bool

HasSessionScope returns true if the scope for the sysVar includes session.

func (*SysVar) SetGlobalFromHook

func (sv *SysVar) SetGlobalFromHook(ctx context.Context, s *SessionVars, val string, skipAliases bool) error

SetGlobalFromHook calls the SetGlobal func if it exists.

func (*SysVar) SetSessionFromHook

func (sv *SysVar) SetSessionFromHook(s *SessionVars, val string) error

SetSessionFromHook calls the SetSession func if it exists.

func (*SysVar) SkipInit

func (sv *SysVar) SkipInit() bool

SkipInit returns true if when a new session is created we should "skip" copying an initial value to it (and call the SetSession func if it exists)

func (*SysVar) SkipSysvarCache

func (sv *SysVar) SkipSysvarCache() bool

SkipSysvarCache returns true if the sysvar should not re-execute on peers This doesn't make sense for the GC variables because they are based in tikv tables. We'd effectively be reading and writing to the same table, which could be in an unsafe manner. In future these variables might be converted to not use a different table internally, but to do that we need to first fix upgrade/downgrade so we know that older servers won't be in the cluster which update only these values.

func (*SysVar) Validate

func (sv *SysVar) Validate(vars *SessionVars, value string, scope vardef.ScopeFlag) (string, error)

Validate checks if system variable satisfies specific restriction.

func (*SysVar) ValidateFromType

func (sv *SysVar) ValidateFromType(vars *SessionVars, value string, scope vardef.ScopeFlag) (string, error)

ValidateFromType provides automatic validation based on the SysVar's type

func (*SysVar) ValidateWithRelaxedValidation

func (sv *SysVar) ValidateWithRelaxedValidation(vars *SessionVars, value string, scope vardef.ScopeFlag) string

ValidateWithRelaxedValidation normalizes values but can not return errors. Normalization+validation needs to be applied when reading values because older versions of TiDB may be less sophisticated in normalizing values. But errors should be caught and handled, because otherwise there will be upgrade issues.

type TableDelta

type TableDelta struct {
	Delta    int64
	Count    int64
	InitTime time.Time // InitTime is the time that this delta is generated.
	TableID  int64
}

TableDelta stands for the changed count for one table or partition.

func (TableDelta) Clone

func (td TableDelta) Clone() TableDelta

Clone returns a cloned TableDelta.

type TableSnapshot

type TableSnapshot struct {
	Rows [][]types.Datum
	Err  error
}

TableSnapshot represents a data snapshot of the table contained in `information_schema`.

type TemporaryTableData

type TemporaryTableData interface {
	kv.Retriever
	// Staging create a new staging buffer inside the MemBuffer.
	// Subsequent writes will be temporarily stored in this new staging buffer.
	// When you think all modifications looks good, you can call `Release` to public all of them to the upper level buffer.
	Staging() kv.StagingHandle
	// Release publish all modifications in the latest staging buffer to upper level.
	Release(kv.StagingHandle)
	// Cleanup cleanups the resources referenced by the StagingHandle.
	// If the changes are not published by `Release`, they will be discarded.
	Cleanup(kv.StagingHandle)
	// GetTableSize get the size of a table
	GetTableSize(tblID int64) int64
	// DeleteTableKey removes the entry for key k from table
	DeleteTableKey(tblID int64, k kv.Key) error
	// SetTableKey sets the entry for k from table
	SetTableKey(tblID int64, k kv.Key, val []byte) error
}

TemporaryTableData is a interface to maintain temporary data in session

func NewTemporaryTableData

func NewTemporaryTableData(memBuffer kv.MemBuffer) TemporaryTableData

NewTemporaryTableData creates a new TemporaryTableData

type TransactionContext

type TransactionContext struct {
	TxnCtxNoNeedToRestore
	TxnCtxNeedToRestore
}

TransactionContext is used to store variables that has transaction scope.

func (*TransactionContext) AddSavepoint

func (tc *TransactionContext) AddSavepoint(name string, memdbCheckpoint *tikv.MemDBCheckpoint)

AddSavepoint adds a new savepoint.

func (*TransactionContext) AddUnchangedKeyForLock

func (tc *TransactionContext) AddUnchangedKeyForLock(key []byte)

AddUnchangedKeyForLock adds an unchanged key for pessimistic lock.

func (*TransactionContext) Cleanup

func (tc *TransactionContext) Cleanup()

Cleanup clears up transaction info that no longer use.

func (*TransactionContext) ClearDelta

func (tc *TransactionContext) ClearDelta()

ClearDelta clears the delta map.

func (*TransactionContext) CollectUnchangedKeysForLock

func (tc *TransactionContext) CollectUnchangedKeysForLock(buf []kv.Key) []kv.Key

CollectUnchangedKeysForLock collects unchanged keys for pessimistic lock.

func (*TransactionContext) DeleteSavepoint

func (tc *TransactionContext) DeleteSavepoint(name string) bool

DeleteSavepoint deletes the savepoint, return false indicate the savepoint name doesn't exists.

func (*TransactionContext) FlushStmtPessimisticLockCache

func (tc *TransactionContext) FlushStmtPessimisticLockCache()

FlushStmtPessimisticLockCache merges the current statement pessimistic lock cache into transaction pessimistic lock cache. The caller may need to clear the stmt cache itself.

func (*TransactionContext) GetCurrentSavepoint

func (tc *TransactionContext) GetCurrentSavepoint() TxnCtxNeedToRestore

GetCurrentSavepoint gets TransactionContext's savepoint.

func (*TransactionContext) GetForUpdateTS

func (tc *TransactionContext) GetForUpdateTS() uint64

GetForUpdateTS returns the ts for update.

func (*TransactionContext) GetKeyInPessimisticLockCache

func (tc *TransactionContext) GetKeyInPessimisticLockCache(key kv.Key) (val []byte, ok bool)

GetKeyInPessimisticLockCache gets a key in pessimistic lock cache.

func (*TransactionContext) ReleaseSavepoint

func (tc *TransactionContext) ReleaseSavepoint(name string) bool

ReleaseSavepoint deletes the named savepoint and the later savepoints, return false indicate the named savepoint doesn't exists.

func (*TransactionContext) RestoreBySavepoint

func (tc *TransactionContext) RestoreBySavepoint(savepoint TxnCtxNeedToRestore)

RestoreBySavepoint restores TransactionContext to the specify savepoint.

func (*TransactionContext) RollbackToSavepoint

func (tc *TransactionContext) RollbackToSavepoint(name string) *SavepointRecord

RollbackToSavepoint rollbacks to the specified savepoint by name.

func (*TransactionContext) SetForUpdateTS

func (tc *TransactionContext) SetForUpdateTS(forUpdateTS uint64)

SetForUpdateTS sets the ts for update.

func (*TransactionContext) SetPessimisticLockCache

func (tc *TransactionContext) SetPessimisticLockCache(key kv.Key, val []byte)

SetPessimisticLockCache sets a key value pair in pessimistic lock cache. The value is buffered in the statement cache until the current statement finishes.

func (*TransactionContext) UpdateDeltaForTable

func (tc *TransactionContext) UpdateDeltaForTable(
	physicalTableID int64,
	delta int64,
	count int64,
)

UpdateDeltaForTable updates the delta info for some table. The `cols` argument is used to update the delta size for cols. If `cols` is nil, it means that the delta size for cols is not changed.

type TxnCtxNeedToRestore

type TxnCtxNeedToRestore struct {
	// TableDeltaMap is used in the schema validator for DDL changes in one table not to block others.
	// It's also used in the statistics updating.
	// Note: for the partitioned table, it stores all the partition IDs.
	TableDeltaMap map[int64]TableDelta

	// CachedTables is not nil if the transaction write on cached table.
	CachedTables map[int64]any

	// InsertTTLRowsCount counts how many rows are inserted in this statement
	InsertTTLRowsCount int
	// contains filtered or unexported fields
}

TxnCtxNeedToRestore stores transaction variables which need to be restored when rolling back to a savepoint.

type TxnCtxNoNeedToRestore

type TxnCtxNoNeedToRestore struct {
	Binlog      any
	InfoSchema  any
	History     any
	StartTS     uint64
	StaleReadTs uint64

	PessimisticCacheHit int

	// CreateTime For metrics.
	CreateTime     time.Time
	StatementCount int
	CouldRetry     bool
	IsPessimistic  bool
	// IsStaleness indicates whether the txn is read only staleness txn.
	IsStaleness bool
	// IsExplicit indicates whether the txn is an interactive txn, which is typically started with a BEGIN
	// or START TRANSACTION statement, or by setting autocommit to 0.
	IsExplicit bool
	Isolation  string
	LockExpire uint32
	ForUpdate  uint32
	// TxnScope indicates the value of txn_scope
	TxnScope string

	// Savepoints contains all definitions of the savepoint of a transaction at runtime, the order of the SavepointRecord is the same with the SAVEPOINT statements.
	// It is used for a lookup when running `ROLLBACK TO` statement.
	Savepoints []SavepointRecord

	// TemporaryTables is used to store transaction-specific information for global temporary tables.
	// It can also be stored in sessionCtx with local temporary tables, but it's easier to clean this data after transaction ends.
	TemporaryTables map[int64]tableutil.TempTable
	// EnableMDL indicates whether to enable the MDL lock for the transaction.
	EnableMDL bool

	// FairLockingUsed marking whether at least one of the statements in the transaction was executed in
	// fair locking mode.
	FairLockingUsed bool
	// FairLockingEffective marking whether at least one of the statements in the transaction was executed in
	// fair locking mode, and it takes effect (which is determined according to whether lock-with-conflict
	// has occurred during execution of any statement).
	FairLockingEffective bool

	// CurrentStmtPessimisticLockCache is the cache for pessimistic locked keys in the current statement.
	// It is merged into `pessimisticLockCache` after a statement finishes.
	// Read results cannot be directly written into pessimisticLockCache because failed statement need to rollback
	// its pessimistic locks.
	CurrentStmtPessimisticLockCache map[string][]byte
	// contains filtered or unexported fields
}

TxnCtxNoNeedToRestore stores transaction variables which do not need to restored when rolling back to a savepoint.

type TxnReadTS

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

TxnReadTS indicates the value and used situation for tx_read_ts

func NewTxnReadTS

func NewTxnReadTS(ts uint64) *TxnReadTS

NewTxnReadTS creates TxnReadTS

func (*TxnReadTS) PeakTxnReadTS

func (t *TxnReadTS) PeakTxnReadTS() uint64

PeakTxnReadTS returns readTS

func (*TxnReadTS) SetTxnReadTS

func (t *TxnReadTS) SetTxnReadTS(ts uint64)

SetTxnReadTS update readTS, and refresh used

func (*TxnReadTS) UseTxnReadTS

func (t *TxnReadTS) UseTxnReadTS() uint64

UseTxnReadTS returns readTS, and mark used as true

type UserVars

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

UserVars is used to provide user variable operations.

func NewUserVars

func NewUserVars() *UserVars

NewUserVars creates a new user UserVars object

func (*UserVars) Clone

func (s *UserVars) Clone() UserVarsReader

Clone clones the user vars

func (*UserVars) GetUserVarType

func (s *UserVars) GetUserVarType(name string) (*types.FieldType, bool)

GetUserVarType get user defined variables' type

func (*UserVars) GetUserVarVal

func (s *UserVars) GetUserVarVal(name string) (types.Datum, bool)

GetUserVarVal get user defined variables' value

func (*UserVars) SetUserVarType

func (s *UserVars) SetUserVarType(name string, ft *types.FieldType)

SetUserVarType set user defined variables' type

func (*UserVars) SetUserVarVal

func (s *UserVars) SetUserVarVal(name string, dt types.Datum)

SetUserVarVal set user defined variables' value

func (*UserVars) UnsetUserVar

func (s *UserVars) UnsetUserVar(varName string)

UnsetUserVar unset an user defined variable by name.

type UserVarsReader

type UserVarsReader interface {
	// GetUserVarVal get user defined variables' value
	GetUserVarVal(name string) (types.Datum, bool)
	// GetUserVarType get user defined variables' type
	GetUserVarType(name string) (*types.FieldType, bool)
	// Clone clones the user vars
	Clone() UserVarsReader
}

UserVarsReader is used to read user defined variables.

type WriteStmtBufs

type WriteStmtBufs struct {
	// RowValBuf is used by tablecodec.EncodeRow, to reduce runtime.growslice.
	RowValBuf []byte
	// AddRowValues use to store temp insert rows value, to reduce memory allocations when importing data.
	AddRowValues []types.Datum

	// IndexValsBuf is used by index.FetchValues
	IndexValsBuf []types.Datum
	// IndexKeyBuf is used by index.GenIndexKey
	IndexKeyBuf []byte
}

WriteStmtBufs can be used by insert/replace/delete/update statement. TODO: use a common memory pool to replace this.

Jump to

Keyboard shortcuts

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