db

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 38 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	SysVarMaxConnections = "max_connections"

	SysVarInnonDBStatsPersist  = "innodb_stats_persistent"
	SysVarSortBufferSize       = "sort_buffer_size"
	SysVarInnoDBBufferPoolSize = "innodb_buffer_pool_size"
)
View Source
const (
	EqRangeIndexDiveLimit56 = 10
	EqRangeIndexDiveLimit   = 200 // MySQL 5.7+ / 8.0+ 默认值
)

MySQL eq_range_index_dive_limit 默认值 当 IN 列表或等值条件数量 < 此阈值时,使用 index dive 当数量 >= 此阈值时,使用 index statistics 估算

MySQL 版本默认值: - MySQL 5.6: 10 - MySQL 5.7+: 200 - MySQL 8.0+: 200

View Source
const (
	// "tinyint", "smallint", "mediumint", "int", "bigint", "integer"
	// 混用 signed 和 unsigned :  有隐式转换风险
	ColDataTypeTinyint   string = "tinyint"
	ColDataTypeSmallint  string = "smallint"
	ColDataTypeMediumint string = "mediumint"
	ColDataTypeInt       string = "int"
	ColDataTypeBigint    string = "bigint"
	ColDataTypeInteger   string = "integer"

	// "decimal",  "numeric"
	ColDataTypeDecimal string = "decimal"
	ColDataTypeNumeric string = "numeric"

	// "float", "double", "real"
	ColDataTypeFloat  string = "float"
	ColDataTypeDouble string = "double"
	ColDataTypeReal   string = "real"

	// "char", "varchar", "text", "tinytext", "mediumtext", "longtext", "enum", "set"
	// CHARACTER_SET_NAME 和COLLATION_NAME要相同
	ColDataTypeChar       string = "char"
	ColDataTypeVarchar    string = "varchar"
	ColDataTypeText       string = "text"
	ColDataTypeTinytext   string = "tinytext"
	ColDataTypeMediumtext string = "mediumtext"
	ColDataTypeLongtext   string = "longtext"
	ColDataTypeEnum       string = "enum"
	ColDataTypeSet        string = "set"

	// datetime
	ColDataTypeDatetime  string = "datetime"
	ColDataTypeTimestamp string = "timestamp"
	ColDataTypeDate      string = "date"
	ColDataTypeTime      string = "time"
	ColDataTypeYear      string = "year"

	// BINARY :
	ColDataTypeVarbinary  string = "varbinary"
	ColDataTypeTinyblob   string = "tinyblob"
	ColDataTypeBlob       string = "blob"
	ColDataTypeMediumblob string = "mediumblob"
	ColDataTypeLONGBLOB   string = "longblob"
)
View Source
const (
	// InnoDB page overhead (FIL Header + FIL Trailer)
	PageOverhead = 46 // 38 bytes header + 8 bytes trailer

	// Default InnoDB page size (16KB)
	DefaultPageSize = 16384

	// Default fill factor (InnoDB keeps 1/16 free for future growth)
	DefaultFillFactor = 0.9375 // 15/16

	// Minimum row length to prevent division by zero
	MinRowLength = 10
)
View Source
const (
	// Default InnoDB page size is 16KB, which typically holds 100-200 rows for normal tables
	DefaultRowsPerPage = 100

	// DefaultMaxSampledRows caps total sampled rows per table across all MySQL versions.
	// It aligns sampler output with DefaultTableInfoCacheConfig().MaxSampledRowsPerEntry.
	DefaultMaxSampledRows = 20000

	// DefaultMaxSampledBytes caps cumulative in-memory sampled row bytes per table
	// while streaming sample windows, preventing wide-row tables from spiking memory
	// before entering the shared cache's MaxSampleBytes budget.
	DefaultMaxSampledBytes int64 = 64 * 1024 * 1024

	// DefaultSamplingTimeout provides a built-in per-table sampling deadline when
	// callers pass a context without a deadline (e.g. context.Background()).
	DefaultSamplingTimeout = 30 * time.Second

	// DefaultSamplePages is the number of application sampling windows for MySQL 5.6 and 5.7.
	// Together with DefaultSampleRangeSize, it stays within DefaultMaxSampledRows.
	DefaultSamplePages = 20

	// Fixed range size for each sampling interval (rows per page)
	// This ensures consistent sampling cost regardless of table size
	DefaultSampleRangeSize = 1000
)
View Source
const (
	// MySQL 8.0 默认直方图桶数
	DefaultHistogramBuckets = 100

	// MySQL80SamplePages is the number of application sampling windows for MySQL 8.0+.
	// Together with DefaultSampleRangeSize, it stays within DefaultMaxSampledRows.
	MySQL80SamplePages = 20
)
View Source
const DefaultSampleMatchCacheMaxEntries = 4096

DefaultSampleMatchCacheMaxEntries bounds per-request sample match memoization.

Variables

View Source
var ErrTableNotFound = errors.New("table not found")

ErrTableNotFound indicates that information_schema.tables returned no row for the requested table (either the table does not exist or the current database user lacks privileges on it).

Functions

func AppendTypedSampleValue

func AppendTypedSampleValue(buffer []byte, value any) ([]byte, bool)

AppendTypedSampleValue appends a type-tagged, self-delimiting binary encoding of one SQL sample cell value to buffer. It returns ok=false for unsupported Go representations (such as monotonic time.Time readings or opaque structs).

func CalculateIndexPages

func CalculateIndexPages(totalRows int64, avgKeyLength int64, pageSize int64, fillFactor float64) int64

CalculateIndexPages calculates the number of pages needed for an index

func ComputeTableInfoFingerprint

func ComputeTableInfoFingerprint(ctx context.Context, info *TableInfo) (fp string, cacheable bool)

ComputeTableInfoFingerprint computes a deterministic, strongly-typed content fingerprint for a single TableInfo snapshot (metadata, page geometry, aggregate statistics, histograms, and raw sampled rows).

It returns cacheable=false when ctx is canceled or when any sampled row contains an unsupported Go value (such as a monotonic time.Time reading or an opaque struct) that cannot be encoded unambiguously.

func EstimateSelectivityWithHistogram

func EstimateSelectivityWithHistogram(histogram *Histogram, operator string, value interface{}) float64

EstimateSelectivityWithHistogram estimates selectivity using histogram (MySQL 8.0)

func GetIndexMeta

func GetIndexMeta(ctx context.Context, db *gorm.DB, database, table string) (*collections.Map[string, *TableIndexMeta], error)

GetIndexMeta loads index metadata from INFORMATION_SCHEMA.STATISTICS, which is authoritative for SUB_PART (prefix width), COLLATION (ASC/DESC), INDEX_TYPE (BTREE/HASH/FULLTEXT), IS_VISIBLE (MySQL 8.0+), and functional expression columns that mysql.innodb_index_stats does not expose.

func GetLowerCaseTableNamesMode

func GetLowerCaseTableNamesMode(ctx context.Context, db *gorm.DB) (relation.CaseMode, error)

GetLowerCaseTableNamesMode reads and strictly validates the server's frozen lower_case_table_names identity mode.

func GetMySQLVersion

func GetMySQLVersion(ctx context.Context, db *gorm.DB) *util.MySQLVersion

func GetRelationCanonicalizer

func GetRelationCanonicalizer(ctx context.Context, db *gorm.DB) (relation.Canonicalizer, error)

GetRelationCanonicalizer reads lower_case_table_names and returns the canonicalizer that must be shared by an Agent and all of its request caches.

func GetSystemVariable

func GetSystemVariable(ctx context.Context, db *gorm.DB, varName string) (string, error)

func IndexDiveLimit

func IndexDiveLimit(tableInfo *TableInfo) int

IndexDiveLimit returns the eq_range_index_dive_limit that gates index dives for tableInfo. A positive TableStats.EqRangeIndexDiveLimit wins. Otherwise MySQL 5.6 statistics use 10 and every other version uses 200. Index dives apply only when the number of equality ranges is strictly below this limit.

func ShowCreateSchema

func ShowCreateSchema(ctx context.Context, db *gorm.DB, schema string) (string, error)

func ShowCreateTableSQL

func ShowCreateTableSQL(ctx context.Context, db *gorm.DB, schema, table string) (string, error)

func ToNumber

func ToNumber(v any) (float64, bool)

toNumber 将值转换为 float64

func ToStringForceUnsafe

func ToStringForceUnsafe(v any) string

func ToStringUnsafe

func ToStringUnsafe(v any) (string, bool)

toString2 将值转换为字符串

func ValuesEqual

func ValuesEqual(a, b any) bool

valuesEqual 比较两个值是否相等

Types

type CatalogIndexPart

type CatalogIndexPart struct {
	FullWidth *bool  `json:"full_width,omitempty"`
	Collation string `json:"collation,omitempty"`
	IndexType string `json:"index_type,omitempty"`
}

CatalogIndexPart holds the observed INFORMATION_SCHEMA.STATISTICS values for one named key part (or the index-level entry keyed by "" for functional key parts). A nil FullWidth means SUB_PART coverage was not collected.

type ColumnDataTypeClass

type ColumnDataTypeClass int
const (
	ColumnDataTypeInt    ColumnDataTypeClass = iota
	ColumnDataTypeFloat  ColumnDataTypeClass = iota
	ColumnDataTypeString ColumnDataTypeClass = iota
	ColumnDataTypeOther  ColumnDataTypeClass = iota
)

type ColumnInfo

type ColumnInfo struct {
	Schema parser.CIStr
	Table  parser.CIStr
	Column parser.CIStr
}

type ColumnStats

type ColumnStats struct {
	Name          string
	DataType      string
	NullCount     int
	DistinctCount int64 // Estimated using MySQL's algorithm
	MinValue      any
	MaxValue      any
	AvgLength     float64
	// contains filtered or unexported fields
}

ColumnStats represents statistical information about a column

func CalculateColumnStatsWithHistogram

func CalculateColumnStatsWithHistogram(pageSamples []*PageSample, columns []*TableColumnMeta,
	totalPages, sampledPages, rowsPerPage int64, histogramConfig *HistogramConfig) ([]*ColumnStats, map[string]*Histogram)

CalculateColumnStatsWithHistogram calculates statistics using histogram (MySQL 8.0)

func (*ColumnStats) GetDistinctCount

func (cs *ColumnStats) GetDistinctCount() int64

type CostConstants

type CostConstants struct {
	HasRowEvaluateCost           bool
	RowEvaluateCost              float64
	HasKeyCompareCost            bool
	KeyCompareCost               float64
	HasDiskTempTableCreateCost   bool
	DiskTempTableCreateCost      float64
	HasDiskTempTableRowCost      bool
	DiskTempTableRowCost         float64
	HasMemoryTempTableCreateCost bool
	MemoryTempTableCreateCost    float64
	HasMemoryTempTableRowCost    bool
	MemoryTempTableRowCost       float64
	HasMemoryBlockReadCost       bool
	MemoryBlockReadCost          float64
	HasIOBlockReadCost           bool
	IOBlockReadCost              float64
}

CostConstants holds immutable MySQL server and engine cost constant overrides observed once per request from mysql.server_cost and mysql.engine_cost.

type DBContext

type DBContext struct {
	Context   context.Context
	Language  string
	Schema    string
	Charset   string
	Collation string

	Version util.MySQLVersion
	// contains filtered or unexported fields
}

func NewDBContext

func NewDBContext(ctx context.Context, db *gorm.DB) *DBContext

func NewDBContextForRequest

func NewDBContextForRequest(
	ctx context.Context,
	pinnedDB *gorm.DB,
	requestDefault string,
	canonicalizer relation.Canonicalizer,
	tableCache *TableInfoLayeredCache,
) *DBContext

NewDBContextForRequest constructs a request-local context around a pinned GORM connection, request default database, and frozen relation canonicalizer. When a shared cache is provided, its frozen canonicalizer is authoritative so local and shared lookup identities cannot diverge.

func NewDBContextForRequestWithVersion

func NewDBContextForRequestWithVersion(
	ctx context.Context,
	pinnedDB *gorm.DB,
	requestDefault string,
	canonicalizer relation.Canonicalizer,
	tableCache *TableInfoLayeredCache,
	version util.MySQLVersion,
) *DBContext

NewDBContextForRequestWithVersion constructs a request-local context using an already observed server version without querying it again. The version is copied, and a shared table cache remains authoritative for relation identity.

func NewDBContextWithTableCache

func NewDBContextWithTableCache(ctx context.Context, db *gorm.DB, tableCache *TableInfoLayeredCache) *DBContext

func (*DBContext) AllRegisteredAnalysisSnapshots

func (ctx *DBContext) AllRegisteredAnalysisSnapshots(infos map[relation.Key]*TableInfo) bool

AllRegisteredAnalysisSnapshots reports whether every entry in infos is an immutable borrowed snapshot registered on ctx from the shared table cache.

func (*DBContext) AttachPool

func (ctx *DBContext) AttachPool(poolDB *gorm.DB)

AttachPool binds an unpinned pool handle for explicit-schema metadata and statistics loading after the pinned session connection has been released.

func (*DBContext) BuildAnalysisVirtualIndex

func (ctx *DBContext) BuildAnalysisVirtualIndex(info *TableInfo, table string, columns []string, unique bool) (*VirtualIndex, error)

BuildAnalysisVirtualIndex reuses the sample-derived part of an index's statistics. The name, known catalog prefixes, uniqueness and key width are still resolved for each requested definition on a private result.

func (*DBContext) Canonicalizer

func (ctx *DBContext) Canonicalizer() relation.Canonicalizer

Canonicalizer returns the frozen relation canonicalizer used by this request.

func (*DBContext) DetachPinnedConnection

func (ctx *DBContext) DetachPinnedConnection()

DetachPinnedConnection detaches the pinned session connection so it cannot outlive its gorm.Connection callback while preserving online-session identity.

func (*DBContext) FreezeMetadataForOffline

func (ctx *DBContext) FreezeMetadataForOffline(globalPool *gorm.DB)

FreezeMetadataForOffline detaches table metadata DB access while retaining an optional unpinned pool handle solely for lazy single-shot global cost config queries (mysql.server_cost, mysql.engine_cost, sort_buffer_size).

func (*DBContext) FreezeOnlineSession

func (ctx *DBContext) FreezeOnlineSession(opts OnlineSessionFreezeOptions)

FreezeOnlineSession eagerly snapshots the selected session settings while still on the pinned connection, then detaches all DB handles so offline computation performs zero database I/O.

func (*DBContext) GetCachedTableInfo

func (ctx *DBContext) GetCachedTableInfo(schemaName, tableName string) (*TableInfo, bool)

GetCachedTableInfo returns already cached table metadata plus aggregate statistics from the request-local or shared cache without querying the database. It returns (nil, false) when only base metadata or no valid cached entry is available.

func (*DBContext) GetContextValue

func (ctx *DBContext) GetContextValue(key string) any

func (*DBContext) GetContextValueString

func (ctx *DBContext) GetContextValueString(key string) string

func (*DBContext) GetCtx

func (ctx *DBContext) GetCtx() context.Context

func (*DBContext) GetDB

func (ctx *DBContext) GetDB() *gorm.DB

func (*DBContext) GetLanguage

func (ac *DBContext) GetLanguage() string

func (*DBContext) GetLocaleCatalog

func (ac *DBContext) GetLocaleCatalog() *sqli18n.Catalog

func (*DBContext) GetSystemVariable

func (ac *DBContext) GetSystemVariable(key string) (string, error)

func (*DBContext) GetTableInfo

func (ctx *DBContext) GetTableInfo(schemaName, tableName string) (*TableInfo, error)

GetTableInfo returns table metadata plus column/index statistics. Use this for callers that need stats but do not require raw sampled pages.

func (*DBContext) GetTableInfoBase

func (ctx *DBContext) GetTableInfoBase(schemaName, tableName string) (*TableInfo, error)

GetTableInfoBase returns only metadata needed for schema-aware features such as column expansion and PK lookup. It intentionally skips stats/samples.

func (*DBContext) GetTableInfoForAnalysis

func (ctx *DBContext) GetTableInfoForAnalysis(schema, table string) (*TableInfo, error)

GetTableInfoForAnalysis retrieves statistics for analysis. The built-in Agent may borrow immutable samples. Other requests receive owned samples. Only views registered here can use the shared statistics derivatives.

func (*DBContext) GetTableInfoWithSamples

func (ctx *DBContext) GetTableInfoWithSamples(schemaName, tableName string) (*TableInfo, error)

GetTableInfoWithSamples returns full metadata, statistics, and sampled pages. Use this only for cost/index what-if paths that depend on PageSamples.

func (*DBContext) GetTableMeta

func (ctx *DBContext) GetTableMeta(schemaName, tableName string) (*TableMeta, error)

func (*DBContext) HasOnlineSession

func (ctx *DBContext) HasOnlineSession() bool

HasOnlineSession reports whether this DBContext observed a live database session, including after detaching the pinned connection for unpinned pool metadata loading or offline computation.

func (*DBContext) InvalidateTableInfo

func (ctx *DBContext) InvalidateTableInfo(schemaName, tableName string)

InvalidateTableInfo removes cached metadata, statistics, and samples for one table from both the request-local cache and the optional shared table cache. Callers that execute DDL or ANALYZE TABLE must invalidate before collecting table information again so cost and what-if evaluation cannot observe a stale physical design or stale statistics.

func (*DBContext) InvalidateTableInfoByKey

func (ctx *DBContext) InvalidateTableInfoByKey(key relation.Key)

InvalidateTableInfoByKey removes request-local and shared entries for one canonical physical relation.

func (*DBContext) IsRegisteredAnalysisSnapshot

func (ctx *DBContext) IsRegisteredAnalysisSnapshot(info *TableInfo) bool

IsRegisteredAnalysisSnapshot reports whether info is an immutable borrowed snapshot registered on ctx from the shared table cache.

func (*DBContext) Localize

func (ac *DBContext) Localize(msg *i18n.Message, args map[string]any) string

func (*DBContext) LowerCaseTableName

func (ac *DBContext) LowerCaseTableName() bool

func (*DBContext) LowerCaseTableNamesMode

func (ac *DBContext) LowerCaseTableNamesMode() (relation.CaseMode, error)

LowerCaseTableNamesMode returns the server's lower_case_table_names mode.

func (*DBContext) ParseOneStmt

func (ac *DBContext) ParseOneStmt(sql string) (ast.StmtNode, error)

func (*DBContext) PrecomputedSnapshotFingerprint

func (ctx *DBContext) PrecomputedSnapshotFingerprint(key relation.Key, info *TableInfo) (fp string, cacheable bool, ok bool)

PrecomputedSnapshotFingerprint returns the single-table typed fingerprint precomputed when info was written into the shared cache. It returns ok=false unless info is an immutable borrowed snapshot registered on ctx for key with a matching sampleRevision and precomputed fingerprint.

func (*DBContext) RelationKey

func (ctx *DBContext) RelationKey(schemaName, tableName string) relation.Key

RelationKey returns the request's canonical lookup identity for a table.

func (*DBContext) ResetSampleMatchCache

func (ctx *DBContext) ResetSampleMatchCache()

ResetSampleMatchCache drops cached sample match counts for this request.

func (*DBContext) SampleMatchCache

func (ctx *DBContext) SampleMatchCache() *SampleMatchCache

SampleMatchCache returns the request-scoped bounded sample match cache, initializing it lazily on first use.

func (*DBContext) SessionCostConstants

func (ctx *DBContext) SessionCostConstants() CostConstants

SessionCostConstants reads mysql.server_cost and mysql.engine_cost at most once per DBContext and returns an immutable snapshot of observed overrides. After metadata freeze, it may borrow a single connection from the unpinned pool on first actual cost consumer access and release it immediately.

func (*DBContext) SessionMaxHeapTableSize

func (d *DBContext) SessionMaxHeapTableSize() (uint64, bool)

SessionMaxHeapTableSize returns the pinned session's weedout planning budget. A failed live read returns (0, true); cached statistics from other sessions cannot replace missing evidence about this connection.

func (*DBContext) SessionSemijoinSwitches

func (d *DBContext) SessionSemijoinSwitches() (OptimizerSwitches, bool)

SessionSemijoinSwitches returns the pinned request's switches. A disconnected analysis uses its recorded table statistics instead. Failed or unloaded reads on a live session return (OptimizerSwitches{}, true) with unknown switch bits and never substitute another session's capture.

func (*DBContext) SessionSortBufferSize

func (ctx *DBContext) SessionSortBufferSize() (int64, bool)

SessionSortBufferSize reads sort_buffer_size at most once per DBContext and returns the cached positive byte size when observed.

func (*DBContext) SetCharset

func (ac *DBContext) SetCharset(charset string) *DBContext

func (*DBContext) SetCollation

func (ac *DBContext) SetCollation(collation string) *DBContext

func (*DBContext) SetContextKV

func (ctx *DBContext) SetContextKV(key string, value any)

func (*DBContext) SetLanguage

func (ac *DBContext) SetLanguage(language string) *DBContext

func (*DBContext) SetLocaleCatalog

func (ac *DBContext) SetLocaleCatalog(catalog *sqli18n.Catalog) *DBContext

func (*DBContext) SetSampleMatchCache

func (ctx *DBContext) SetSampleMatchCache(cache *SampleMatchCache)

SetSampleMatchCache replaces the request-scoped sample match cache.

func (*DBContext) SnapshotOptimizerSession

func (ctx *DBContext) SnapshotOptimizerSession()

SnapshotOptimizerSession reads @@optimizer_switch and @@SESSION.max_heap_table_size once on the pinned session connection.

func (*DBContext) ValidDB

func (ctx *DBContext) ValidDB() bool

type Histogram

type Histogram struct {
	ColumnName         string
	Buckets            []HistogramBucket
	SamplingRate       float64
	NullValuesFraction float64 // Fraction of NULL rows in [0.0, 1.0]
	HistogramType      string  // "singleton" or "equi-height"
	DataType           string  // "numeric", "string", "datetime", "binary"
	CharsetName        string  // e.g., "utf8mb4"
	CollationName      string  // e.g., "utf8mb4_general_ci"
}

Histogram represents a column histogram (MySQL 8.0+). Bucket cumulative frequencies represent unconditional full-table probabilities over all observed rows (including NULLs), so NonNullMass() + NullValuesFraction == 1.0 when the histogram covers the entire distribution.

func (*Histogram) HasCompleteMass

func (h *Histogram) HasCompleteMass() bool

HasCompleteMass reports whether the histogram's non-NULL bucket mass plus NullValuesFraction accounts for the full population within floating-point tolerance.

func (*Histogram) NonNullMass

func (h *Histogram) NonNullMass() float64

NonNullMass returns the cumulative non-NULL probability mass covered by the histogram's buckets, clamped to [0, 1].

type HistogramBucket

type HistogramBucket struct {
	BucketNumber  int
	LowerBound    interface{}
	UpperBound    interface{}
	Frequency     float64 // Cumulative full-table frequency (0.0 to 1.0)
	DistinctCount int
}

HistogramBucket represents a single bucket in the histogram

type HistogramConfig

type HistogramConfig struct {
	// NumBuckets is the number of buckets in the histogram (default 100)
	// Corresponds to the number specified in ANALYZE TABLE ... UPDATE HISTOGRAM ON ... WITH N BUCKETS
	NumBuckets int
}

HistogramConfig holds histogram generation configuration In MySQL 8.0, these parameters can be configured via system variables or ANALYZE TABLE options

func DefaultHistogramConfig

func DefaultHistogramConfig() *HistogramConfig

DefaultHistogramConfig returns the default histogram configuration This matches MySQL 8.0's default behavior

func NewHistogramConfigFromDB

func NewHistogramConfigFromDB(db *gorm.DB, schema, table string) *HistogramConfig

NewHistogramConfigFromDB 从 MySQL 获取特定表的直方图配置

func NewHistogramConfigFromDBWithContext

func NewHistogramConfigFromDBWithContext(ctx context.Context, db *gorm.DB, schema, table string) *HistogramConfig

NewHistogramConfigFromDBWithContext loads histogram configuration for schema.table using ctx (falling back to DefaultSamplingTimeout when ctx has no deadline).

type IndexColMeta

type IndexColMeta struct {
	IndexName   string
	ColumnName  string
	ColumnNameL string
	IsUnique    bool
	IsPrimary   bool
	SeqInIndex  int
	Cardinality int64
	// contains filtered or unexported fields
}

func (*IndexColMeta) IndexType

func (meta *IndexColMeta) IndexType() string

IndexType returns the recorded INFORMATION_SCHEMA.STATISTICS.INDEX_TYPE value.

func (*IndexColMeta) IsExpression

func (part *IndexColMeta) IsExpression() bool

IsExpression reports whether this key part is a functional expression rather than a plain table column (MySQL 8.0+ sets COLUMN_NAME to NULL).

func (*IndexColMeta) IsInvisible

func (part *IndexColMeta) IsInvisible() bool

IsInvisible reports whether MySQL 8.0+ catalog metadata marked the owning index invisible (INFORMATION_SCHEMA.STATISTICS.IS_VISIBLE = 'NO').

func (*IndexColMeta) PartOrder

func (meta *IndexColMeta) PartOrder() IndexPartOrder

PartOrder returns the catalog key properties recorded on this column metadata.

type IndexColumn

type IndexColumn struct {
	Name     string
	NameL    string
	Position int // Position in the index (1-based)
	// contains filtered or unexported fields
}

IndexColumn represents a column in an index

type IndexDiveEstimator

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

IndexDiveEstimator 使用 PageSamples 模拟 MySQL index dive 算法

MySQL index dive 工作原理: 1. 对于等值条件 (col = value),MySQL 会实际探测 B+tree 索引 2. 调用 handler::records_in_range() 来估算范围内的行数 3. 这比使用统计信息更准确,但有 I/O 开销

模拟实现: 1. 已收集的 PageSamples 数据(来自 sampleTablePages80WithMethod) 2. 在样本中统计匹配特定值的行数 3. 外推到全表:matchedCount * totalRows / sampledRows

参考 MySQL 源码: - sql/handler.cc: handler::records_in_range() - sql/range_optimizer/range_scan_plan.cc: get_ranges_eclasses() - storage/innobase/handler/ha_innodb.cc: records_in_range()

func NewIndexDiveEstimator

func NewIndexDiveEstimator(tableInfo *TableInfo) *IndexDiveEstimator

NewIndexDiveEstimator 创建一个新的 IndexDiveEstimator

func NewIndexDiveEstimatorWithCache

func NewIndexDiveEstimatorWithCache(tableInfo *TableInfo, cache *SampleMatchCache) *IndexDiveEstimator

NewIndexDiveEstimatorWithCache creates an IndexDiveEstimator backed by a request-scoped SampleMatchCache.

func NewIndexDiveEstimatorWithLimit

func NewIndexDiveEstimatorWithLimit(tableInfo *TableInfo, limit int) *IndexDiveEstimator

NewIndexDiveEstimatorWithLimit 创建带有自定义阈值的 IndexDiveEstimator

func NewIndexDiveEstimatorWithLimitAndCache

func NewIndexDiveEstimatorWithLimitAndCache(tableInfo *TableInfo, limit int, cache *SampleMatchCache) *IndexDiveEstimator

NewIndexDiveEstimatorWithLimitAndCache creates an IndexDiveEstimator with both a custom dive limit and an optional request-scoped SampleMatchCache.

func (*IndexDiveEstimator) EstimateEqualityRows

func (e *IndexDiveEstimator) EstimateEqualityRows(columnL string, value any) *IndexDiveResult

EstimateEqualityRows 估算等值条件 (col = value) 的匹配行数

MySQL 行为: - 单个等值条件总是使用 index dive(1 < eq_range_index_dive_limit) - 通过实际探测索引来获取更准确的估算

我们的实现: - 在 PageSamples 中统计匹配值的行数 - 外推到全表

func (*IndexDiveEstimator) EstimateInListRows

func (e *IndexDiveEstimator) EstimateInListRows(columnL string, values []any) *IndexDiveResult

EstimateInListRows 估算 IN 条件 (col IN (v1, v2, ...)) 的匹配行数

MySQL 行为: - 如果 IN 列表元素数 < eq_range_index_dive_limit,使用 index dive - 如果 >= eq_range_index_dive_limit,使用 index statistics

参考:MySQL 源码 sql/range_optimizer/range_scan_plan.cc

func (*IndexDiveEstimator) EstimateRangeRows

func (e *IndexDiveEstimator) EstimateRangeRows(columnL string, lower, upper any, includeLower, includeUpper bool) *IndexDiveResult

EstimateRangeRows 估算范围条件的匹配行数

支持的条件类型: - col > value, col >= value - col < value, col <= value - col BETWEEN lower AND upper

func (*IndexDiveEstimator) ShouldUseIndexDive

func (e *IndexDiveEstimator) ShouldUseIndexDive(numConditions int) bool

ShouldUseIndexDive 判断是否应该使用 index dive numConditions 是等值条件的数量(对于 IN 列表,是列表元素数)

type IndexDiveResult

type IndexDiveResult struct {
	// EstimatedRows 是估算的匹配行数
	EstimatedRows int64
	// Selectivity 是选择性 (0-1)
	Selectivity float64
	// UsedIndexDive 表示是否使用了 index dive(vs 使用统计信息)
	UsedIndexDive bool
	// SampledMatches 是在样本中找到的匹配数
	SampledMatches int64
	// TotalSampled 是样本中的总行数
	TotalSampled int64
}

IndexDiveResult 表示 index dive 的结果

type IndexPartOrder

type IndexPartOrder struct {
	FullWidth   bool
	WidthKnown  bool
	Expression  bool   // the catalog key part is a functional expression, not a plain column.
	Direction   string // ASC or DESC for a catalog key part.
	MethodKnown bool   // the catalog identifies the index access method.
	Unordered   bool   // the catalog identifies a non-BTREE access method.
}

IndexPartOrder records physical key properties known from the catalog. An empty direction or an unknown width is possible for a historical snapshot.

type IndexStats

type IndexStats struct {
	Name string
	//tableStats          *TableStats
	Columns []*IndexColumn

	IsUnique            bool
	IsPrimary           bool
	Cardinality         int64   // Estimated number of unique values (full index)
	PrefixCardinalities []int64 // Cardinality for each prefix: (a), (a,b), (a,b,c), etc.

	AvgRowsPerKey float64 // Average number of rows per distinct key value
	IndexPages    int64   // Estimated number of index pages
	LeafPages     int64   // Estimated number of leaf pages
	TreeHeight    int     // Estimated B-tree height
	KeyLength     int64   // Maximum encoded key length used by index-only read cost
	Selectivity   float64 // Selectivity ratio (0-1, lower means more selective)
	// ClusterFactor describes how scattered table rows are when the index is
	// traversed in key order. 0 means clustered/sequential and 1 means random.
	// The value is sampled from page data when available and is used to price
	// secondary-index row lookups and MRR locality.
	ClusterFactor      float64
	ClusterFactorValid bool
	// contains filtered or unexported fields
}

IndexStats represents statistics about an index

func (*IndexStats) GetTreeHeight

func (is *IndexStats) GetTreeHeight() int

type OnlineSessionFreezeOptions

type OnlineSessionFreezeOptions struct {
	CostConstants    bool
	SortBufferSize   bool
	OptimizerSession bool
}

OnlineSessionFreezeOptions selects which live session values should be read once and frozen before releasing the request's pinned DB connection.

type OptimizerSwitches

type OptimizerSwitches struct {
	// SemijoinKnown and SemijoinEnabled retain explicitly observed session
	// switches. Older snapshots omit both masks.
	SemijoinKnown   SemijoinSwitch `json:"SemijoinKnown,omitempty"`
	SemijoinEnabled SemijoinSwitch `json:"SemijoinEnabled,omitempty"`

	// UseIndexExtensions records that the captured session enabled index extensions.
	// Older snapshots omit this field and provide no evidence of support.
	UseIndexExtensions bool `json:"UseIndexExtensions,omitempty"`

	// ConditionFanoutFilter controls whether condition filtering is used in join optimization
	// When OFF, condition filtering returns COND_FILTER_ALLPASS (1.0) for all conditions
	// Default: ON in MySQL 5.7+ and MySQL 8.0+
	ConditionFanoutFilter bool

	// Other optimizer switches that may affect cost estimation
	IndexMerge              bool
	IndexMergeUnion         bool
	IndexMergeSort          bool
	IndexMergeIntersection  bool
	EngineConditionPushdown bool
	IndexConditionPushdown  bool
	MRR                     bool
	MRRCostBased            bool
	BatchedKeyAccess        bool
	BlockNestedLoop         bool
	UseInvisibleIndexes     bool
	SkipScan                bool
	HashJoin                bool
	Subquery                bool
	DerivedMerge            bool
	PreferOrderingIndex     bool
}

OptimizerSwitches represents MySQL optimizer switch settings These affect how the optimizer estimates selectivity and cost

func DefaultOptimizerSwitches

func DefaultOptimizerSwitches() *OptimizerSwitches

DefaultOptimizerSwitches returns MySQL 8.0 default optimizer_switch values. Unknown versions and non-MySQL servers use this baseline.

func DefaultOptimizerSwitchesFor

func DefaultOptimizerSwitchesFor(version *util.MySQLVersion) *OptimizerSwitches

DefaultOptimizerSwitchesFor returns the optimizer_switch baseline for version. MySQL 5.6 uses 5.6.23 defaults, MySQL 5.7 uses 5.7 defaults (with 8.0-only switches off), and MySQL 8.0.x respects feature introduction patch levels. Unknown versions and non-MySQL servers keep the MySQL 8.0 defaults.

func GetOptimizerSwitches

func GetOptimizerSwitches(db *gorm.DB) *OptimizerSwitches

GetOptimizerSwitches reads optimizer_switch using the MySQL 8.0 baseline. Returns default settings if the database query fails.

func GetOptimizerSwitchesFor

func GetOptimizerSwitchesFor(db *gorm.DB, version *util.MySQLVersion) *OptimizerSwitches

GetOptimizerSwitchesFor reads optimizer_switch and overlays only the flags present in the server string onto the baseline for version.

func GetOptimizerSwitchesForWithContext

func GetOptimizerSwitchesForWithContext(ctx context.Context, db *gorm.DB, version *util.MySQLVersion) *OptimizerSwitches

GetOptimizerSwitchesForWithContext reads optimizer_switch using ctx and overlays only the flags present in the server string onto the baseline for version.

func GetOptimizerSwitchesWithContext

func GetOptimizerSwitchesWithContext(ctx context.Context, db *gorm.DB) *OptimizerSwitches

GetOptimizerSwitchesWithContext reads optimizer_switch using ctx and the MySQL 8.0 baseline. Returns default settings if the database query fails.

func ParseOptimizerSwitch

func ParseOptimizerSwitch(switchStr string) *OptimizerSwitches

ParseOptimizerSwitch parses an optimizer_switch string onto the MySQL 8.0 baseline. Only flags present in switchStr change that baseline.

func ParseOptimizerSwitchFor

func ParseOptimizerSwitchFor(switchStr string, version *util.MySQLVersion) *OptimizerSwitches

ParseOptimizerSwitchFor parses an optimizer_switch string onto the baseline selected by version. Flags absent from switchStr keep that baseline.

func (*OptimizerSwitches) UsesIndexExtensions

func (s *OptimizerSwitches) UsesIndexExtensions() bool

UsesIndexExtensions reports whether the captured session enables implicit InnoDB index key extensions. An unknown setting does not prove eligibility.

type PageConfig

type PageConfig struct {
	// MySQL configuration
	PageSize   int64   // InnoDB page size in bytes (4KB, 8KB, 16KB, 32KB, 64KB)
	FillFactor float64 // Percentage of page used (default ~93.75% = 15/16)

	// Table-specific metrics
	AvgRowLength int64 // Average row size in bytes from INFORMATION_SCHEMA
	DataLength   int64 // Total data size in bytes
	TotalRows    int64 // Total number of rows

	// Calculated values
	UsableSpace    int64 // Usable space per page after overhead
	RowsPerPage    int64 // Calculated rows that fit per page
	EstimatedPages int64 // Total pages needed for the table
}

PageConfig holds InnoDB page configuration and calculated metrics

func GetPageConfig

func GetPageConfig(ctx context.Context, db *gorm.DB, database, tableName string, totalRows int64) (*PageConfig, error)

GetPageConfig retrieves InnoDB page configuration and calculates dynamic page metrics. The version is unknown, so @@innodb_fill_factor is still queried and a missing variable is ignored. Known MySQL versions before 5.7 use getPageConfig, which skips that variable and keeps DefaultFillFactor.

func (*PageConfig) GetEstimatedPages

func (pc *PageConfig) GetEstimatedPages() int64

GetEstimatedPages returns the calculated total pages for a table

func (*PageConfig) GetPageSize

func (pc *PageConfig) GetPageSize() int64

func (*PageConfig) GetRowsPerPage

func (pc *PageConfig) GetRowsPerPage() int64

GetRowsPerPage returns the calculated rows per page for a table

type PageSample

type PageSample struct {
	Rows        []map[string]any // @TODO 列存
	PageNumber  int
	RecordCount int
	ApproxBytes int64
	PageSource  PageSampleSource
}

PageSample represents a sampled page of data

type PageSampleSource

type PageSampleSource uint8

PageSampleSource identifies how PageSample.PageNumber was obtained.

const (
	// PageSampleSourceUnknown indicates page-number provenance was not recorded.
	PageSampleSourceUnknown PageSampleSource = iota
	// PageSampleSourcePhysical indicates PageNumber identifies a real physical data page.
	PageSampleSourcePhysical
	// PageSampleSourceCalibratedProxy indicates PageNumber comes from a calibrated
	// physical-layout proxy (such as an ordered page-partitioned fixture).
	PageSampleSourceCalibratedProxy
	// PageSampleSourceLogicalWindow indicates PageNumber is only a logical SQL
	// range/offset sampling window ordinal and does not prove distinct physical pages.
	PageSampleSourceLogicalWindow
)

func (PageSampleSource) HasPhysicalPageOrder

func (s PageSampleSource) HasPhysicalPageOrder() bool

HasPhysicalPageOrder reports whether PageSample.PageNumber represents physical or calibrated physical-layout page identities suitable for clustering-factor estimation.

type PartitionMeta

type PartitionMeta struct {
	Name                   string
	Method                 string
	Expression             string
	Description            string
	OrdinalPosition        int
	SubpartitionName       string
	SubpartitionMethod     string
	SubpartitionExpression string
	SubpartitionOrdinal    int
	Rows                   int64
	DataLength             int64
	IndexLength            int64
}

PartitionMeta contains the optimizer-relevant subset of information_schema.PARTITIONS. Rows and byte sizes are estimates reported by MySQL and are therefore used only to scope an existing table estimate.

func GetPartitionMeta

func GetPartitionMeta(ctx context.Context, db *gorm.DB, schema, table string) ([]*PartitionMeta, error)

GetPartitionMeta returns named partitions only. For a non-partitioned table information_schema.PARTITIONS exposes a row whose PARTITION_NAME is NULL; that row is intentionally omitted.

type SampleMatchCache

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

SampleMatchCache provides request-scoped, bounded, concurrency-safe reuse of page-sample match counts across baseline and candidate evaluations.

func NewSampleMatchCache

func NewSampleMatchCache(maxEntries int) *SampleMatchCache

NewSampleMatchCache constructs a bounded cache. maxEntries <= 0 disables storing results while still recording scan and row-comparison counters.

func (*SampleMatchCache) Len

func (c *SampleMatchCache) Len() int

Len returns the current number of cached entries.

func (*SampleMatchCache) LookupOrComputeExistenceInt

func (c *SampleMatchCache) LookupOrComputeExistenceInt(info *TableInfo, column string, target int64, compute func() (float64, bool, int64)) (float64, bool)

LookupOrComputeExistenceInt caches exact integer existence sample frequency for a table snapshot and column.

func (*SampleMatchCache) LookupOrComputeExistenceString

func (c *SampleMatchCache) LookupOrComputeExistenceString(info *TableInfo, column, collation, normalizedValue string, compute func() (float64, bool, int64)) (float64, bool)

LookupOrComputeExistenceString caches collation-aware string existence sample frequency for a table snapshot, column, collation, and normalized target.

func (*SampleMatchCache) Reset

func (c *SampleMatchCache) Reset()

Reset clears all cached entries without resetting lifetime counters.

func (*SampleMatchCache) Stats

Stats returns a snapshot of scan, row-comparison, and cache-hit counters.

func (*SampleMatchCache) WithScope

func (c *SampleMatchCache) WithScope(contentScope string) *SampleMatchCache

WithScope returns a lightweight view sharing the same bounded storage and counters while isolating cache keys by contentScope (e.g. a stats content fingerprint for unregistered mutable TableInfo inputs).

type SampleMatchStats

type SampleMatchStats struct {
	Scans           int64
	RowsCompared    int64
	CacheHits       int64
	CacheMisses     int64
	SkippedDueToCap int64
}

SampleMatchStats reports sample-scan activity for one request-scoped cache.

type SamplingIndex

type SamplingIndex struct {
	Name        string
	Columns     []string
	Column1     *TableColumnMeta
	IsComposite bool
	Priority    int // Lower is better
	// contains filtered or unexported fields
}

SamplingIndex represents the selected index for sampling

func (*SamplingIndex) LeadingColType

func (si *SamplingIndex) LeadingColType() ColumnDataTypeClass

type SamplingMethod

type SamplingMethod string

SamplingMethod represents the sampling algorithm to use

const (
	// SamplingMethodRandom uses MySQL's Random Dive algorithm
	// - Completely random selection
	// - Statistically unbiased
	// - MySQL's official approach
	SamplingMethodRandom SamplingMethod = "random"

	// SamplingMethodSystematic uses fixed-interval systematic sampling
	// - Evenly distributed intervals
	// - Predictable performance
	// - Better coverage but may be biased if data has periodicity
	SamplingMethodSystematic SamplingMethod = "systematic"
)

type SchemaMeta

type SchemaMeta struct {
	Catalog   string
	Name      string
	Character string
	Collation string
	SQLPath   string
}

func GetSchemaMeta

func GetSchemaMeta(ctx context.Context, db *gorm.DB, schema string) (*SchemaMeta, error)

type SemijoinSwitch

type SemijoinSwitch uint8

SemijoinSwitch identifies a session switch governing a semijoin plan.

const (
	// SemijoinTransform controls transformation of subquery predicates.
	SemijoinTransform SemijoinSwitch = 1 << iota
	// SemijoinFirstMatch enables FirstMatch in the semijoin nest.
	SemijoinFirstMatch
	// SemijoinLooseScan enables ordered group elimination.
	SemijoinLooseScan
	// SemijoinWeedout enables DuplicateWeedout.
	SemijoinWeedout
	// SemijoinMaterialize enables materialization strategies.
	SemijoinMaterialize
	// SemijoinBuffer enables the physical hash semijoin on MySQL 8.0.20+.
	SemijoinBuffer
)

type TableColumnInfo

type TableColumnInfo struct {
	Meta  *TableColumnMeta
	Stats *ColumnStats
}

type TableColumnMeta

type TableColumnMeta struct {
	TableCatalog           string
	TableSchema            string
	TableName              string
	Name                   string
	NameL                  string
	OrdinalPosition        uint64
	ColumnDefault          string
	IsNullable             bool
	DataType               string // varchar
	CharacterMaximumLength int64
	CharacterOctetLength   int64
	NumericPrecision       int64
	NumericScale           int64
	DatetimePrecision      int64
	CharacterSetName       string
	CollationName          string
	ColumnType             string // varchar(50)
	ColumnKey              string
	Extra                  string
	Privileges             string
	ColumnComment          string
	IsGenerated            string
	GenerationExpression   string

	PrimaryKey    bool
	UniqueKey     bool
	AutoIncrement bool
	DataTypeClass ColumnDataTypeClass
}

func GetTableColumnMeta

func GetTableColumnMeta(ctx context.Context, db *gorm.DB, schema, table string) ([]*TableColumnMeta, error)

func (*TableColumnMeta) GetCharset

func (col *TableColumnMeta) GetCharset() string

func (*TableColumnMeta) GetDataType

func (col *TableColumnMeta) GetDataType() string

func (*TableColumnMeta) GetType

func (col *TableColumnMeta) GetType() ColumnDataTypeClass

func (*TableColumnMeta) IndexKeyAlwaysFullWidth

func (column *TableColumnMeta) IndexKeyAlwaysFullWidth() bool

IndexKeyAlwaysFullWidth reports whether MySQL disallows a prefix length for this type.

type TableIndexInfo

type TableIndexInfo struct {
	//TableInfo *TableInfo
	// Cons              *ast.Constraint
	Meta  *TableIndexMeta
	Stats *IndexStats
}

func (*TableIndexInfo) CatalogPartSnapshot

func (idx *TableIndexInfo) CatalogPartSnapshot() map[string]CatalogIndexPart

CatalogPartSnapshot copies the recorded physical properties by column for this index. Missing catalog values stay absent in older or partial records. Functional expression parts preserve their index-level IndexType under "".

func (*TableIndexInfo) GetColumnsL

func (ti *TableIndexInfo) GetColumnsL() []string

func (*TableIndexInfo) GetFirstColumnL

func (ti *TableIndexInfo) GetFirstColumnL() string

func (*TableIndexInfo) WithCatalogPartSnapshot

func (idx *TableIndexInfo) WithCatalogPartSnapshot(parts map[string]CatalogIndexPart) *TableIndexInfo

WithCatalogPartSnapshot restores observations against the named columns and functional expression parts of this index without modifying the source metadata shared by other snapshots. Omitted fields (nil FullWidth, empty Collation or IndexType) leave previously recorded values intact.

type TableIndexMeta

type TableIndexMeta struct {
	Table   string
	Name    string
	Columns []*IndexColMeta
}

func (*TableIndexMeta) IsInvisible

func (m *TableIndexMeta) IsInvisible() bool

IsInvisible reports whether MySQL 8.0+ catalog metadata marked this index invisible (INFORMATION_SCHEMA.STATISTICS.IS_VISIBLE = 'NO').

type TableInfo

type TableInfo struct {
	Meta       *TableMeta
	Stats      *TableStats
	PageConfig *PageConfig

	// Options   []*ast.TableOption
	// Partition *ast.PartitionOptions
	Columns            []*TableColumnInfo
	ColIndexes         map[string][]*TableIndexInfo
	FirstColIndexes    map[string][]*TableIndexInfo
	CompositeIndexCols map[string][]*TableIndexInfo
	Indexes            []*TableIndexInfo

	// CreateTableSQL is the server-returned SHOW CREATE TABLE definition.
	// Collection is best-effort so metadata analysis can continue when the
	// connected account cannot read the definition.
	CreateTableSQL   string
	CreateTableError string
	// contains filtered or unexported fields
}

func CollectTableInfoWithHistogramConfig

func CollectTableInfoWithHistogramConfig(ctx context.Context, db *gorm.DB, database, table string, version util.MySQLVersion, samplingMethod SamplingMethod, histogramConfig *HistogramConfig) (*TableInfo, error)

CollectTableStatsWithHistogramConfig collects statistics with custom histogram configuration

func CollectTableInfoWithOptions

func CollectTableInfoWithOptions(ctx context.Context, db *gorm.DB, database, table string, version util.MySQLVersion, samplingMethod SamplingMethod) (*TableInfo, error)

CollectTableStatsWithOptions collects statistics with full control over sampling

func CollectTableInfoWithVersion

func CollectTableInfoWithVersion(ctx context.Context, db *gorm.DB, database, table string, version util.MySQLVersion) (*TableInfo, error)

CollectTableStatsWithVersion collects statistics with specific MySQL version algorithm Uses Random sampling method by default (MySQL's approach)

func CollectTableInfoWithoutStats

func CollectTableInfoWithoutStats(ctx context.Context, db *gorm.DB, database, table string) (*TableInfo, error)

CollectTableStatsWithHistogramConfig collects statistics with custom histogram configuration If histogramConfig is nil, it will be read from database or use defaults

func CollectTableStatsByTableMetaWithHistogramConfig

func CollectTableStatsByTableMetaWithHistogramConfig(ctx context.Context, db *gorm.DB, meta *TableInfo, version util.MySQLVersion, samplingMethod SamplingMethod, histogramConfig *HistogramConfig) (*TableInfo, error)

func NewTableInfo

func NewTableInfo(meta *TableMeta) *TableInfo

func (*TableInfo) BuildVirtualIndex

func (ti *TableInfo) BuildVirtualIndex(tableName string, columns []string, isUnique bool) (*VirtualIndex, error)

func (*TableInfo) GetAutoIncrementColumn

func (ti *TableInfo) GetAutoIncrementColumn() *TableColumnMeta

func (*TableInfo) GetAvgRowLength

func (ti *TableInfo) GetAvgRowLength() int64

func (*TableInfo) GetBufferPoolSize

func (ti *TableInfo) GetBufferPoolSize() int64

func (*TableInfo) GetColumn

func (ti *TableInfo) GetColumn(colNameL string) *TableColumnMeta

func (*TableInfo) GetColumnHistogram

func (ti *TableInfo) GetColumnHistogram(column string) *Histogram

func (*TableInfo) GetColumnNames

func (ti *TableInfo) GetColumnNames() []string

func (*TableInfo) GetColumnNamesL

func (ti *TableInfo) GetColumnNamesL() []string

func (*TableInfo) GetColumnStats

func (ti *TableInfo) GetColumnStats(colNameL string) *ColumnStats

GetColumnStats

func (*TableInfo) GetCompositeIndexMetasByCol

func (ti *TableInfo) GetCompositeIndexMetasByCol(colNameL string) []*TableIndexMeta

func (*TableInfo) GetDataLength

func (ti *TableInfo) GetDataLength() int64

GetDataLength returns the total data file size in bytes. This is used for cost estimation to calculate page counts and memory estimates.

func (*TableInfo) GetHistogram

func (ti *TableInfo) GetHistogram() map[string]*Histogram

func (*TableInfo) GetIndexCount

func (ti *TableInfo) GetIndexCount() int

func (*TableInfo) GetIndexMetasByFirstCol

func (ti *TableInfo) GetIndexMetasByFirstCol(colNameL string) []*TableIndexMeta

func (*TableInfo) GetIndexStats

func (ti *TableInfo) GetIndexStats() []*IndexStats

func (*TableInfo) GetIndexesByCol

func (ti *TableInfo) GetIndexesByCol(colNameL string) []*TableIndexInfo

func (*TableInfo) GetIndexesByFirstCol

func (ti *TableInfo) GetIndexesByFirstCol(colNameL string) []*TableIndexInfo

func (*TableInfo) GetPageConfig

func (ti *TableInfo) GetPageConfig() *PageConfig

func (*TableInfo) GetPageSampleCount

func (ti *TableInfo) GetPageSampleCount() int

func (*TableInfo) GetPrimaryKeyColumns

func (ti *TableInfo) GetPrimaryKeyColumns(schema, tableName string) []string

func (*TableInfo) GetRowsPerPage

func (ti *TableInfo) GetRowsPerPage() float64

GetRowsPerPage

func (*TableInfo) GetSchemaName

func (ti *TableInfo) GetSchemaName() string

func (*TableInfo) GetSchemaNameL

func (ti *TableInfo) GetSchemaNameL() string

func (*TableInfo) GetStats

func (ti *TableInfo) GetStats() *TableStats

GetStats

func (*TableInfo) GetTableColumns

func (ti *TableInfo) GetTableColumns(schema, tableName string) []string

func (*TableInfo) GetTableName

func (ti *TableInfo) GetTableName() string

func (*TableInfo) GetTableNameL

func (ti *TableInfo) GetTableNameL() string

func (*TableInfo) GetTableRows

func (ti *TableInfo) GetTableRows() int64

GetTableRows

func (*TableInfo) GetTotalPages

func (ti *TableInfo) GetTotalPages() int64

GetTotalPages

func (*TableInfo) GetVirtualIndexes

func (ti *TableInfo) GetVirtualIndexes() []*VirtualIndex

func (*TableInfo) HasIndexOnColumn

func (ti *TableInfo) HasIndexOnColumn(colNameL string) bool

func (*TableInfo) HasPageSamples

func (ti *TableInfo) HasPageSamples() bool

func (*TableInfo) HasStats

func (ti *TableInfo) HasStats() bool

func (*TableInfo) IndexPartCoversValue

func (ti *TableInfo) IndexPartCoversValue(index *VirtualIndex, part int) bool

IndexPartCoversValue reports whether a lookup compares the whole column. Hypothetical keys are built from full columns. Old catalog entries can only prove this property for types MySQL does not allow to be prefix-indexed.

func (*TableInfo) PrimaryIndex

func (ti *TableInfo) PrimaryIndex() *VirtualIndex

PrimaryIndex returns the declared primary key in catalog key-part order.

func (*TableInfo) PrimaryKeyPartOrder

func (ti *TableInfo) PrimaryKeyPartOrder(column string) IndexPartOrder

PrimaryKeyPartOrder reports the physical properties of a clustered key part. InnoDB copies the clustered key's direction into implicit secondary-index parts.

type TableInfoCacheConfig

type TableInfoCacheConfig struct {
	// BaseLayer caches table metadata + column/index stats (without raw samples).
	BaseTTL        time.Duration
	MaxBaseEntries int

	// SampleLayer caches raw sampled pages for short-term reuse.
	EnableSampleLayer bool
	SampleTTL         time.Duration
	MaxSampleEntries  int
	// MaxSampleBytes limits total memory budget of sample layer (estimated bytes).
	// Non-positive means unlimited.
	MaxSampleBytes int64
	// MaxSampledRowsPerEntry limits one sample entry size. Non-positive means unlimited.
	MaxSampledRowsPerEntry int

	// SweepInterval controls background expired-entry cleanup cadence.
	// Non-positive disables background sweeper.
	SweepInterval time.Duration
}

TableInfoCacheConfig controls shared table statistics cache behavior.

func DefaultTableInfoCacheConfig

func DefaultTableInfoCacheConfig() *TableInfoCacheConfig

DefaultTableInfoCacheConfig returns the default layered table cache configuration, bounded to DefaultMaxSampledRows (20,000) raw sampled rows per table across all versions.

type TableInfoLayeredCache

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

TableInfoLayeredCache is a process-level shared layered cache.

func NewTableInfoLayeredCache

func NewTableInfoLayeredCache(cfg *TableInfoCacheConfig) *TableInfoLayeredCache

NewTableInfoLayeredCache constructs a cache with the historical case-insensitive, lowercase lookup behavior.

func NewTableInfoLayeredCacheWithCanonicalizer

func NewTableInfoLayeredCacheWithCanonicalizer(cfg *TableInfoCacheConfig, canonicalizer relation.Canonicalizer) *TableInfoLayeredCache

NewTableInfoLayeredCacheWithCanonicalizer constructs a cache whose relation identity rules remain frozen for the lifetime of the cache.

func (*TableInfoLayeredCache) Canonicalizer

func (c *TableInfoLayeredCache) Canonicalizer() relation.Canonicalizer

Canonicalizer returns the immutable relation canonicalizer used by the cache.

func (*TableInfoLayeredCache) Close

func (c *TableInfoLayeredCache) Close()

Close stops the background sweeper and drops cached table metadata and samples. It is safe to call repeatedly and concurrently.

func (*TableInfoLayeredCache) GetTableInfo

func (c *TableInfoLayeredCache) GetTableInfo(schemaName, tableName string) (*TableInfo, bool)

func (*TableInfoLayeredCache) GetTableInfoByKey

func (c *TableInfoLayeredCache) GetTableInfoByKey(key relation.Key) (*TableInfo, bool)

GetTableInfoByKey returns an independent copy of cached table information.

func (*TableInfoLayeredCache) InvalidateRelation

func (c *TableInfoLayeredCache) InvalidateRelation(key relation.Key)

InvalidateRelation removes every cached detail level for one canonical relation key.

func (*TableInfoLayeredCache) InvalidateTable

func (c *TableInfoLayeredCache) InvalidateTable(schemaName, tableName string)

func (*TableInfoLayeredCache) InvalidateTableAll

func (c *TableInfoLayeredCache) InvalidateTableAll(schemaName, tableName string)

func (*TableInfoLayeredCache) SetTableInfo

func (c *TableInfoLayeredCache) SetTableInfo(schemaName, tableName string, ti *TableInfo)

func (*TableInfoLayeredCache) SetTableInfoByKey

func (c *TableInfoLayeredCache) SetTableInfoByKey(key relation.Key, ti *TableInfo)

SetTableInfoByKey explicitly replaces cached table information under a canonical relation key.

Sample-layer caching supports first-class SQL scalar values (nil, bool, numeric types, string, []byte, time.Time) and bounded nested []any / map[string]any values, matching cloneCacheValue's deep-copy isolation domain. If a PageSample omits ApproxBytes (<= 0) and contains unsupported opaque Go types or excessively deep containers, the sample layer is skipped and only base metadata and aggregate statistics are cached; callers that intentionally store custom values may pre-populate ApproxBytes > 0.

type TableMeta

type TableMeta struct {
	Catalog       string
	Schema        string
	Name          string
	Type          string
	Engine        string
	Version       int64
	RowFormat     string
	Rows          int64
	AvgRowLength  int64
	DataLength    int64
	MaxDataLength int64
	IndexLength   int64
	DataFree      int64
	AutoIncrement int64
	CreateTime    time.Time
	UpdateTime    time.Time
	CheckTime     time.Time
	Collation     string
	Checksum      int64
	CreateOptions string
	Comment       string

	Columns    []*TableColumnMeta
	ColumnMap  *collections.Map[string, *TableColumnMeta]
	Indexes    *collections.Map[string, *TableIndexMeta]
	Partitions []*PartitionMeta
}

func GetTableMeta

func GetTableMeta(ctx context.Context, db *gorm.DB, schema, table string) (*TableMeta, error)

func (*TableMeta) GetColumn

func (t *TableMeta) GetColumn(nameL string) *TableColumnMeta

func (*TableMeta) GetIndex

func (t *TableMeta) GetIndex(name string) *TableIndexMeta

func (*TableMeta) GetIndexByCol

func (t *TableMeta) GetIndexByCol(colNameL string) []*TableIndexMeta

type TableStats

type TableStats struct {
	Database          string
	Table             string
	TotalRows         int64
	TotalPages        int64
	RowsPerPage       int64 // Dynamic rows per page based on actual row size
	SampledPages      int
	SamplingMethod    string
	MySQLVersion      util.MySQLVersion
	BufferPoolSize    int64  // InnoDB buffer pool size from innodb_buffer_pool_size
	JoinBufferSize    int64  // join_buffer_size used by BKA batching
	MaxHeapTableSize  uint64 `json:",omitempty"` // Captured session limit for weedout planning, zero when unavailable.
	ReadRndBufferSize int64  // read_rnd_buffer_size used as the MRR row-id buffer budget
	// EqRangeIndexDiveLimit is the server eq_range_index_dive_limit captured
	// with these statistics. Zero means it was not captured; IndexDiveLimit
	// then uses 10 for MySQL 5.6 statistics and 200 otherwise.
	EqRangeIndexDiveLimit int
	Columns               []*ColumnStats

	Indexes     []*IndexStats         // Index information
	Histograms  map[string]*Histogram // MySQL 8.0+ only
	PageSamples []*PageSample         // Raw sampled data for composite index cardinality calculation; treat as read-only when sourced from cache

	OptimizerSwitches *OptimizerSwitches // MySQL optimizer switch settings
	// contains filtered or unexported fields
}

TableStats represents comprehensive statistics for a table

func (*TableStats) GetBufferPoolSize

func (ts *TableStats) GetBufferPoolSize() int64

GetBufferPoolSize returns the InnoDB buffer pool size. Returns 0 if not set (caller should use default constant).

func (*TableStats) GetColumnStats

func (ts *TableStats) GetColumnStats(colName string) *ColumnStats

func (*TableStats) GetIndexes

func (ts *TableStats) GetIndexes() []*IndexStats

func (*TableStats) GetPageSamples

func (ts *TableStats) GetPageSamples() []*PageSample

func (*TableStats) GetRowsPerPage

func (ts *TableStats) GetRowsPerPage() float64

func (*TableStats) InitColumnsMap

func (ts *TableStats) InitColumnsMap()

InitColumnsMap initializes the internal columnsMap from the Columns slice. This is useful when TableStats is created externally and needs the columnsMap to be populated for GetColumnStats to work correctly.

type VirtualIndex

type VirtualIndex struct {
	TableO   string
	TableL   string
	Name     string
	ColumnsL []string // lower column name
	ColumnsO []string

	IsUnique   bool
	IsPrimary  bool
	Statistics *IndexStats
	Exist      bool
	// contains filtered or unexported fields
}

VirtualIndex represents a hypothetical index that doesn't exist yet

func CreateVirtualIndex

func CreateVirtualIndex(tableName string, columns []string, tableStats *TableStats, isUnique bool) (*VirtualIndex, error)

CreateVirtualIndex creates a virtual index based on column statistics and sampled data

func NewVirtualIndex

func NewVirtualIndex(table, name string, columnO []string, stats *IndexStats) *VirtualIndex

func TableIndexesInfo2VirtualIndexes

func TableIndexesInfo2VirtualIndexes(indexes []*TableIndexInfo) []*VirtualIndex

func (*VirtualIndex) ContainsColumn

func (vi *VirtualIndex) ContainsColumn(columnL string) bool

func (*VirtualIndex) GetStatistics

func (index *VirtualIndex) GetStatistics() *IndexStats

func (*VirtualIndex) HasFullWidthPart

func (index *VirtualIndex) HasFullWidthPart(part int) bool

HasFullWidthPart reports whether index statistics record full-width coverage for this specific key part. Missing historical evidence returns false.

func (*VirtualIndex) PartOrder

func (index *VirtualIndex) PartOrder(part int) IndexPartOrder

PartOrder returns the recorded ordering evidence for the given key position.

Jump to

Keyboard shortcuts

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