Documentation
¶
Overview ¶
result_model.go defines the public boundary between native EXPLAIN facts and internal whole-query what-if predictions. Keeping these representations separate prevents callers from comparing incompatible absolute cost units.
Index ¶
- Constants
- Variables
- func BuildPublicReport(facts *OptimizeResult, engine analysis.AnalysisContext, ...) *analysis.AnalyzeResult
- func CheckExplainSupport(sql string) error
- func RenderMessage(catalog *sqli18n.Catalog, lang string, ref *MessageRef) string
- func ToPublicEvaluation(w *WhatIfEvaluation, context analysis.AnalysisContext) analysis.EvaluationReport
- func ToPublicIssue(old *Issue) *analysis.Issue
- func ToPublicSuggestions(old *Issue) []*analysis.Suggestion
- type AdvisorContext
- type AgentConfig
- type AnalysisSource
- type AnalysisStatus
- type AnalyzeContext
- func (ctx *AnalyzeContext) EnsureExplainJSON() *explain.ExplainResult
- func (ctx *AnalyzeContext) EnsureTableInfos() map[relation.Key]*db.TableInfo
- func (ctx *AnalyzeContext) GetCTEExecutionModeForRef(ref *explain.VirtualTable) CTEExecutionMode
- func (ctx *AnalyzeContext) HasDB() bool
- func (ctx *AnalyzeContext) HasExplain() bool
- func (ctx *AnalyzeContext) IsEnabled(name string) bool
- func (ctx *AnalyzeContext) Localize(msg *i18n.Message, args map[string]any) string
- func (ctx *AnalyzeContext) PeekExplainJSON() *explain.ExplainResult
- func (ctx *AnalyzeContext) PeekTableInfos() map[relation.Key]*db.TableInfo
- func (ctx *AnalyzeContext) ResolveCTEColumnToPhysical(tableNameL, colNameL string) (*db.TableInfo, string)
- func (ctx *AnalyzeContext) ResolveTableColumnToPhysical(tableNameL, colNameL string) (*db.TableInfo, string)
- func (ctx *AnalyzeContext) TableInfo(key relation.Key) *db.TableInfo
- func (ctx *AnalyzeContext) TableInfoOf(table *explain.VirtualTable) *db.TableInfo
- type AnalyzeOption
- func WithAnalyzeCanonicalizer(canonicalizer relation.Canonicalizer) AnalyzeOption
- func WithAnalyzeCatalog(catalog *sqli18n.Catalog) AnalyzeOption
- func WithAnalyzeDefaultDatabase(database string) AnalyzeOption
- func WithAnalyzeReport(context analysis.AnalysisContext, options analysis.RequestOptions) AnalyzeOption
- func WithAnalyzeRuleFilter(f RuleFilter) AnalyzeOption
- func WithAnalyzeRuleSet(rs *RuleSet) AnalyzeOption
- func WithAnalyzeServerMajor(major int) AnalyzeOption
- func WithAnalyzeUnprobedServer() AnalyzeOption
- type AnalyzerRequires
- type BaselineAlignment
- type CTEColumnBinding
- type CTEEntry
- type CTEExecutionMode
- type CTERule
- type CTESemantics
- type CacheTrace
- type CandidateCounts
- type CandidateDecision
- type CandidateDecisionRecord
- type CandidateDisposition
- type CandidateEvaluationSummary
- type CandidateKind
- type CandidateOutcome
- type CandidateReason
- type CandidateRelationEvidence
- type CandidateScenario
- type CandidateScenarioAction
- type CandidateSearchStrategy
- type CandidateSearchSummary
- type CandidateSource
- type CandidateSourcePredicate
- type CandidateStage
- type CandidateTableStatistics
- type ConstraintChangeTrace
- type CostModelIdentity
- type DMLRule
- type DesignTrace
- type Diagnostic
- type ExplainFloat64
- type ExplainInt64
- type ExplainRow
- type ExplainRowIssue
- type ExplainRule
- type ExplainRuleLevel
- type ExplainRuleResult
- type ExplainString
- type ExplainThresholdConfig
- type GroupByOrderByRule
- type HintChangeOperation
- type IndexColumnEvidence
- type IndexEvidence
- type IndexKeyPart
- type IndexSpec
- type Issue
- type IssueCategory
- type IssueType
- type JoinRule
- type JoinStaticRule
- type MessageRef
- type ModelAccessSnapshot
- type ModelPlanEstimate
- type NativeAccessSnapshot
- type NativeExplainBaseline
- type OpportunityKind
- type OpportunityTarget
- type OptimizationConfig
- type OptimizationOpportunity
- type OptimizationTrace
- type OptimizeResult
- type Optimizer
- func (o *Optimizer) Analyze(dbCtx *db.DBContext, sql string) (*OptimizeResult, error)
- func (o *Optimizer) AnalyzePreparedWithOptions(dbCtx *db.DBContext, sql string, stmt parser.StmtNode, opts ...AnalyzeOption) (*OptimizeResult, error)
- func (o *Optimizer) AnalyzeStatic(sql string, lang string, opts ...AnalyzeOption) (*OptimizeResult, error)
- func (o *Optimizer) AnalyzeStaticFacts(sql string, lang string, analyzeOpts *analyzeOptions, catalog *sqli18n.Catalog) (*OptimizeResult, error)
- func (o *Optimizer) AnalyzeStaticPublic(sql string, lang string, opts ...AnalyzeOption) (*analysis.AnalyzeResult, error)
- func (o *Optimizer) AnalyzeWithOptions(dbCtx *db.DBContext, sql string, opts ...AnalyzeOption) (*OptimizeResult, error)
- func (o *Optimizer) ExplainRows(dbCtx *db.DBContext, sql string) ([]ExplainRow, error)
- func (o *Optimizer) PrepareAnalysis(ctx context.Context, sql, lang string, options ...AnalyzeOption) (*PreparedAnalysis, error)
- func (o *Optimizer) Registry() *Registry
- type PlanTrace
- type PostProcessor
- type PredictedChange
- type PreparedAnalysis
- func (p *PreparedAnalysis) BindCanonicalizer(c relation.Canonicalizer) error
- func (p *PreparedAnalysis) CollectOnlineEvidence(dbCtx *db.DBContext) error
- func (p *PreparedAnalysis) CollectOnlineMetadata() error
- func (p *PreparedAnalysis) CollectOnlineSessionEvidence(dbCtx *db.DBContext) error
- func (p *PreparedAnalysis) Continue(dbCtx *db.DBContext) (*OptimizeResult, error)
- func (p *PreparedAnalysis) ExplainArtifact() ([]ExplainRow, error)
- func (p *PreparedAnalysis) FinishOnline() (*OptimizeResult, error)
- func (p *PreparedAnalysis) OnlineApplicable() bool
- func (p *PreparedAnalysis) OnlineEvidenceStatus() (metadata, explain string)
- func (p *PreparedAnalysis) OnlineFactsAvailable() bool
- func (p *PreparedAnalysis) ResetSessionCollectionForRetry() bool
- func (p *PreparedAnalysis) SessionExplainError() error
- func (p *PreparedAnalysis) StaticFacts() *OptimizeResult
- type Registry
- func (r *Registry) AllRuleNames() []string
- func (r *Registry) DisableRule(name string)
- func (r *Registry) EnableRule(name string)
- func (r *Registry) PostProcessors() []PostProcessor
- func (r *Registry) RegisterPostProcessor(pp PostProcessor)
- func (r *Registry) RegisterRule(rule Rule)
- func (r *Registry) Rules() []Rule
- type RejectedPlan
- type RelationRef
- type Rule
- type RuleCheck
- type RuleChecks
- type RuleDescriptor
- type RuleFilter
- type RulePolicy
- type RuleResult
- type RuleSet
- type SQLStyleRule
- type SortGroupRule
- type StatementClass
- type StatsTrace
- type SubqueryRule
- type SugAction
- type Suggestion
- type SuggestionHintChange
- type SuggestionType
- type TableIndexRule
- type TableStructure
- type ValidationTrace
- type WhatIfCandidateIndex
- type WhatIfEvaluation
- type WhatIfScope
- type WhatIfStatus
- type WhatIfSuggestionRejection
- type WhatIfSuggestionRejectionCode
- type WhereAuditRule
Constants ¶
const ( SQLExplainHeaderKeyExtra = "Extra" SQLExplainRuleExtraTemporary = "sql_explain_rule_extra_using_temporary" SQLExplainRuleExtraFileSort = "sql_explain_rule_extra_using_filesort" SQLExplainHeaderKeyRows = "rows" SQLExplainRuleRowsMax = "sql_explain_rule_rows_max" SQLExplainHeaderKeyFilter = "filtered" SQLExplainRuleFilterMin = "sql_explain_rule_filter_min" )
Variables ¶
var ( OptForceIndexMessage = &i18n.Message{ ID: "OptForceIndexMessage", Other: "Using FORCE INDEX({{.Indexes}}), may prevent optimizer from choosing a better index", } OptForceIndexDetail = &i18n.Message{ ID: "OptForceIndexDetail", Other: "Using FORCE INDEX({{.Indexes}})", } OptForceIndexDetailScanRows = &i18n.Message{ ID: "OptForceIndexDetailScanRows", Other: "Using FORCE INDEX({{.Indexes}}), estimated {{.Rows}} rows scanned", } OptIgnoreIndexMessage = &i18n.Message{ ID: "OptIgnoreIndexMessage", Other: "Using IGNORE INDEX({{.Indexes}}), may prevent using the optimal index", } OptIgnoreIndexDetail = &i18n.Message{ ID: "OptIgnoreIndexDetail", Other: "Using IGNORE INDEX({{.Indexes}})", } OptIgnoreIndexDetailFullScan = &i18n.Message{ ID: "OptIgnoreIndexDetailFullScan", Other: "Using IGNORE INDEX({{.Indexes}}), current plan is full table scan, the ignored index may be effective", } OptFuncOnColMessage = &i18n.Message{ ID: "OptFuncOnColMessage", Other: "Function {{.Func}}() wrapping indexed column {{.Column}} will invalidate the index", } OptFuncOnColDetail = &i18n.Message{ ID: "OptFuncOnColDetail", Other: "WHERE condition uses function {{.Func}}() on column {{.Column}}, may invalidate the index", } OptFuncOnColDetailConfirmed = &i18n.Message{ ID: "OptFuncOnColDetailConfirmed", Other: "WHERE condition uses function {{.Func}}() on column {{.Column}}, may invalidate the index (EXPLAIN confirmed: full table scan)", } OptArithOnColMessage = &i18n.Message{ ID: "OptArithOnColMessage", Other: "Arithmetic operation on indexed column {{.Column}} will invalidate the index", } OptArithOnColDetail = &i18n.Message{ ID: "OptArithOnColDetail", Other: "WHERE condition performs arithmetic on column {{.Column}}, move the operation to the value side", } OptLikeWildcardMessage = &i18n.Message{ ID: "OptLikeWildcardMessage", Other: "LIKE pattern starts with wildcard, cannot use index on column {{.Column}}", } OptLikeWildcardDetail = &i18n.Message{ ID: "OptLikeWildcardDetail", Other: "Leading-wildcard LIKE cannot form a B-tree prefix range. Evaluate indexes on other filters and join keys while retaining LIKE as a residual predicate. Full-text search and prefix matching are not equivalent replacements; verify search semantics before rewriting.", } OptImplicitConvMessage = &i18n.Message{ ID: "OptImplicitConvMessage", Other: "Implicit type conversion on column {{.Table}}.{{.Column}} may invalidate the index", } OptImplicitConvDetail = &i18n.Message{ ID: "OptImplicitConvDetail", Other: "Column type is {{.DataType}}, value type mismatch, recommend unifying data types", } )
var ( OptSelectStarMessage = &i18n.Message{ ID: "OptSelectStarMessage", Other: "SELECT * may read unnecessary columns", } OptSelectStarDetail = &i18n.Message{ ID: "OptSelectStarDetail", Other: "Specify only needed columns to reduce network transfer and IO overhead, and enable covering index usage", } OptLimitNoOrderByMessage = &i18n.Message{ ID: "OptLimitNoOrderByMessage", Other: "Using LIMIT without ORDER BY, result set order is indeterminate", } OptLimitNoOrderByDetail = &i18n.Message{ ID: "OptLimitNoOrderByDetail", Other: "LIMIT queries without ORDER BY may return different results under different execution plans", } )
var ( OptFullTableScanMessage = &i18n.Message{ ID: "OptFullTableScanMessage", Other: "Table {{.Table}} performing full table scan, estimated {{.Rows}} rows", } OptFullTableScanDetail = &i18n.Message{ ID: "OptFullTableScanDetail", Other: "Full table scan reads every row in the table, severely impacts performance for large tables", } OptIndexNotUsedMessage = &i18n.Message{ ID: "OptIndexNotUsedMessage", Other: "Table {{.Table}} has candidate indexes but none are used", } OptIndexNotUsedDetail = &i18n.Message{ ID: "OptIndexNotUsedDetail", Other: "Candidate indexes: {{.PossibleKeys}}, but the optimizer chose a full table scan", } OptPoorSelectivityMessage = &i18n.Message{ ID: "OptPoorSelectivityMessage", Other: "Table {{.Table}} uses index {{.Key}} but selectivity is poor (scanning {{.Ratio}}% of rows)", } OptPoorSelectivityDetail = &i18n.Message{ ID: "OptPoorSelectivityDetail", Other: "Index {{.Key}} estimated {{.Rows}} rows / total {{.TotalRows}} = {{.Ratio}}%, insufficient selectivity", } OptCoveringIndexMissedMessage = &i18n.Message{ ID: "OptCoveringIndexMissedMessage", Other: "Table {{.Table}} index {{.Key}} does not cover query columns, needs {{.MissingCount}} additional column lookups", } OptCoveringIndexMissedDetail = &i18n.Message{ ID: "OptCoveringIndexMissedDetail", Other: "Missing columns: {{.MissingCols}}, extending index can avoid table lookups", } OptLeftPrefixMessage = &i18n.Message{ ID: "OptLeftPrefixMessage", Other: "Composite index {{.Index}} violates leftmost prefix rule", } OptLeftPrefixDetail = &i18n.Message{ ID: "OptLeftPrefixDetail", Other: "Index {{.Index}}({{.IndexCols}}) prefix column {{.FirstCol}} is not used in WHERE condition", } )
var ( OptJoinFullScanMessage = &i18n.Message{ ID: "OptJoinFullScanMessage", Other: "Table {{.Table}} uses {{.AccessType}} access method in JOIN, estimated {{.Rows}} rows", } OptJoinFullScanDetail = &i18n.Message{ ID: "OptJoinFullScanDetail", Other: "Table uses full table scan or full index scan, indicating JOIN condition column may lack an index", } OptBadDriverTableMessage = &i18n.Message{ ID: "OptBadDriverTableMessage", Other: "Driver table {{.Driver}}({{.DriverRows}} rows) is much larger than driven table {{.Inner}}({{.InnerRows}} rows), consider swapping JOIN order", } OptBadDriverTableDetail = &i18n.Message{ ID: "OptBadDriverTableDetail", Other: "Driver table rows / driven table rows = {{.Ratio}}, recommend using smaller table as driver", } OptJoinBufferMessage = &i18n.Message{ ID: "OptJoinBufferMessage", Other: "Table {{.Table}} JOIN uses join buffer ({{.Buffer}})", } OptJoinBufferDetail = &i18n.Message{ ID: "OptJoinBufferDetail", Other: "EXPLAIN reports buffered join processing. Its behavior and cost depend on the join algorithm and input sizes; buffer use alone does not prove missing indexes or a full scan for every input row.", } OptJoinNoIndexMessage = &i18n.Message{ ID: "OptJoinNoIndexMessage", Other: "Table {{.Table}} JOIN columns ({{.Columns}}) lack index coverage", } OptJoinNoIndexDetail = &i18n.Message{ ID: "OptJoinNoIndexDetail", Other: "Missing index coverage limits index lookup alternatives for this join. Whether an index helps depends on the join algorithm, join order, and selectivity; it does not imply a full scan for every input row.", } OptJoinCTEFullScanMessage = &i18n.Message{ ID: "OptJoinCTEFullScanMessage", Other: "CTE {{.CTE}} is full-scanned in JOIN ({{.AccessType}}), estimated {{.Rows}} rows", } OptJoinCTEFullScanDetail = &i18n.Message{ ID: "OptJoinCTEFullScanDetail", Other: "CTE materialized table lacks auto-generated index for the JOIN condition. Consider: 1) rewrite CTE as derived table to allow MySQL merge optimization; 2) ensure JOIN column types match; 3) reduce CTE result set size", } )
var ( OptJoinMaxTableMessage = &i18n.Message{ ID: "OptJoinMaxTableMessage", Other: "JOIN involves {{.JoinTableCount}} tables, exceeding the maximum of {{.MaxJoinTableCount}}", } OptJoinMaxTableDetail = &i18n.Message{ ID: "OptJoinMaxTableDetail", Other: "Too many JOIN tables increases query complexity and execution cost, recommend splitting the query or reducing JOIN count", } OptJoinNoConditionMessage = &i18n.Message{ ID: "OptJoinNoConditionMessage", Other: "JOIN without ON condition, may produce Cartesian product", } OptJoinNoConditionDetail = &i18n.Message{ ID: "OptJoinNoConditionDetail", Other: "JOIN without ON condition generates Cartesian product of all rows from both tables, severely impacting performance", } OptJoinWhereColNoAliasMessage = &i18n.Message{ ID: "OptJoinWhereColNoAliasMessage", Other: "JOIN ON condition column lacks table alias prefix", } OptJoinWhereColNoAliasDetail = &i18n.Message{ ID: "OptJoinWhereColNoAliasDetail", Other: "In JOIN queries, ON condition columns should use table alias prefix to avoid ambiguity", } OptJoinFieldNoAliasMessage = &i18n.Message{ ID: "OptJoinFieldNoAliasMessage", Other: "JOIN SELECT field lacks table alias prefix", } OptJoinFieldNoAliasDetail = &i18n.Message{ ID: "OptJoinFieldNoAliasDetail", Other: "In JOIN queries, SELECT fields should use table alias prefix to avoid ambiguity and improve readability", } OptJoinFieldWildcardMessage = &i18n.Message{ ID: "OptJoinFieldWildcardMessage", Other: "JOIN query uses SELECT *, recommend specifying columns explicitly", } OptJoinFieldWildcardDetail = &i18n.Message{ ID: "OptJoinFieldWildcardDetail", Other: "SELECT * in JOIN queries reads all columns from all joined tables, increasing IO and network overhead", } OptJoinOnOpColMessage = &i18n.Message{ ID: "OptJoinOnOpColMessage", Other: "JOIN ON condition has function or arithmetic operation on column, may prevent index usage", } OptJoinOnOpColDetail = &i18n.Message{ ID: "OptJoinOnOpColDetail", Other: "Function or arithmetic on JOIN ON column invalidates the index, recommend moving operations to the value side", } OptJoinBlockedExistingIndexDetail = &i18n.Message{ ID: "OptJoinBlockedExistingIndexDetail", Other: "`{{.Expression}}` prevents `{{.Index}}` from serving this JOIN side", } OptJoinOnNotIndexASTMessage = &i18n.Message{ ID: "OptJoinOnNotIndexASTMessage", Other: "JOIN ON column {{.Table}}.{{.Column}} lacks an index", } OptJoinOnNotIndexASTDetail = &i18n.Message{ ID: "OptJoinOnNotIndexASTDetail", Other: "JOIN ON column without index causes full table scan for each driver table row, recommend creating index", } OptJoinOnColTypeMismatchMessage = &i18n.Message{ ID: "OptJoinOnColTypeMismatchMessage", Other: "JOIN ON columns {{.Columns}} have different data types ({{.LeftType}} vs {{.RightType}}), may cause implicit conversion", } OptJoinOnColTypeMismatchDetail = &i18n.Message{ ID: "OptJoinOnColTypeMismatchDetail", Other: "JOIN ON columns with different data types trigger implicit conversion, preventing index usage and degrading performance", } OptJoinOnColCharsetMismatchMessage = &i18n.Message{ ID: "OptJoinOnColCharsetMismatchMessage", Other: "JOIN ON columns {{.Columns}} have different character sets ({{.LeftCharset}} vs {{.RightCharset}})", } OptJoinOnColCharsetMismatchDetail = &i18n.Message{ ID: "OptJoinOnColCharsetMismatchDetail", Other: "JOIN ON columns with different character sets trigger implicit conversion, preventing index usage, recommend unifying character sets", } OptJoinCrossSchemaMessage = &i18n.Message{ ID: "OptJoinCrossSchemaMessage", Other: "JOIN references tables across databases ({{.Schemas}}), cross-database JOIN is forbidden", } OptJoinCrossSchemaDetail = &i18n.Message{ ID: "OptJoinCrossSchemaDetail", Other: "Cross-database JOIN increases coupling and operational risk, recommend querying within one database or syncing data before joining", } )
var ( OptFilesortMessage = &i18n.Message{ ID: "OptFilesortMessage", Other: "Query on table {{.Table}} triggered filesort, estimated {{.Rows}} rows to sort", } OptFilesortDetail = &i18n.Message{ ID: "OptFilesortDetail", Other: "Filesort requires extra memory and CPU to sort result set, recommend avoiding via index", } OptTempTableMessage = &i18n.Message{ ID: "OptTempTableMessage", Other: "Query on table {{.Table}} uses a temporary table", } OptTempTableDetail = &i18n.Message{ ID: "OptTempTableDetail", Other: "Temporary tables typically occur with GROUP BY, DISTINCT, or certain ORDER BY scenarios, increasing memory and IO overhead", } OptSortGroupNoIndexMessage = &i18n.Message{ ID: "OptSortGroupNoIndexMessage", Other: "{{.Type}} columns ({{.Columns}}) not covered by index, causing {{.Effect}}", } OptSortGroupNoIndexDetail = &i18n.Message{ ID: "OptSortGroupNoIndexDetail", Other: "Recommend creating composite index with WHERE equality columns + {{.Type}} columns", } )
var ( OptGroupByTooManyItemsMessage = &i18n.Message{ ID: "OptGroupByTooManyItemsMessage", Other: "GROUP BY has {{.Count}} columns, too many items may impact performance", } OptGroupByTooManyItemsDetail = &i18n.Message{ ID: "OptGroupByTooManyItemsDetail", Other: "GROUP BY columns exceed threshold (max {{.Max}}), recommend reducing GROUP BY columns or restructuring the query", } OptGroupByOpOnItemMessage = &i18n.Message{ ID: "OptGroupByOpOnItemMessage", Other: "GROUP BY item uses function or arithmetic operation, may prevent index usage", } OptGroupByOpOnItemDetail = &i18n.Message{ ID: "OptGroupByOpOnItemDetail", Other: "GROUP BY with function/arithmetic expressions cannot leverage index for grouping, recommend using plain columns", } OptGroupByDiffTableMessage = &i18n.Message{ ID: "OptGroupByDiffTableMessage", Other: "GROUP BY columns reference multiple tables", } OptGroupByDiffTableDetail = &i18n.Message{ ID: "OptGroupByDiffTableDetail", Other: "GROUP BY columns from different tables typically requires temporary table, recommend grouping by columns from a single table", } OptGroupByConstOrOrdinalMessage = &i18n.Message{ ID: "OptGroupByConstOrOrdinalMessage", Other: "GROUP BY item uses constant or ordinal position", } OptGroupByConstOrOrdinalDetail = &i18n.Message{ ID: "OptGroupByConstOrOrdinalDetail", Other: "GROUP BY should use explicit column references; constants or ordinal positions reduce readability and may cause unstable semantics", } OptGroupByNoOrderByMessage = &i18n.Message{ ID: "OptGroupByNoOrderByMessage", Other: "GROUP BY query has no ORDER BY clause", } OptGroupByNoOrderByDetail = &i18n.Message{ ID: "OptGroupByNoOrderByDetail", Other: "If result order matters, add explicit ORDER BY (typically using GROUP BY columns) to ensure deterministic output order", } OptGroupByNondeterministicMessage = &i18n.Message{ ID: "OptGroupByNondeterministicMessage", Other: "Non-deterministic GROUP BY: non-aggregated columns not in GROUP BY ({{.Columns}})", } OptGroupByNondeterministicDetail = &i18n.Message{ ID: "OptGroupByNondeterministicDetail", Other: "SELECT list contains columns that are neither aggregated nor listed in GROUP BY, which can produce unstable row values", } OptOrderByTooManyItemsMessage = &i18n.Message{ ID: "OptOrderByTooManyItemsMessage", Other: "ORDER BY has {{.Count}} columns, too many items may impact performance", } OptOrderByTooManyItemsDetail = &i18n.Message{ ID: "OptOrderByTooManyItemsDetail", Other: "ORDER BY columns exceed threshold (max {{.Max}}), recommend reducing ORDER BY columns", } OptOrderByOpOnItemMessage = &i18n.Message{ ID: "OptOrderByOpOnItemMessage", Other: "ORDER BY item uses function or arithmetic operation, may prevent index usage", } OptOrderByOpOnItemDetail = &i18n.Message{ ID: "OptOrderByOpOnItemDetail", Other: "ORDER BY with function/arithmetic expressions cannot leverage index for sorting, recommend using plain columns", } OptOrderByConstItemMessage = &i18n.Message{ ID: "OptOrderByConstItemMessage", Other: "ORDER BY item uses constant value", } OptOrderByConstItemDetail = &i18n.Message{ ID: "OptOrderByConstItemDetail", Other: "ORDER BY constants are not allowed, recommend sorting by explicit columns", } OptOrderByNotColumnMessage = &i18n.Message{ ID: "OptOrderByNotColumnMessage", Other: "ORDER BY item is not a column reference", } OptOrderByNotColumnDetail = &i18n.Message{ ID: "OptOrderByNotColumnDetail", Other: "ORDER BY with non-column expressions (constants, subqueries, etc.) may produce unexpected results", } OptOrderByMixedAscDescMessage = &i18n.Message{ ID: "OptOrderByMixedAscDescMessage", Other: "ORDER BY mixes ASC and DESC directions", } OptOrderByMixedAscDescDetail = &i18n.Message{ ID: "OptOrderByMixedAscDescDetail", Other: "Mixed ORDER BY directions may prevent index-ordered scan on older MySQL versions, consider consistent sort direction or matching composite index", } OptOrderByColumnLengthMessage = &i18n.Message{ ID: "OptOrderByColumnLengthMessage", Other: "ORDER BY column {{.Column}} has character length {{.Length}}, sorting on long columns is inefficient", } OptOrderByColumnLengthDetail = &i18n.Message{ ID: "OptOrderByColumnLengthDetail", Other: "Column character length exceeds threshold (max {{.Max}}), sorting on long string columns increases memory and CPU overhead", } )
var ( OptDependentSubqueryMessage = &i18n.Message{ ID: "OptDependentSubqueryMessage", Other: "Dependent subquery (DEPENDENT SUBQUERY) detected, executes once per outer row", } OptDependentSubqueryDetail = &i18n.Message{ ID: "OptDependentSubqueryDetail", Other: "Dependent subquery cost = outer rows × subquery cost, recommend rewriting as JOIN", } OptExpensiveMaterializeMessage = &i18n.Message{ ID: "OptExpensiveMaterializeMessage", Other: "Materialized subquery has high cost ({{.Cost}})", } OptExpensiveMaterializeDetail = &i18n.Message{ ID: "OptExpensiveMaterializeDetail", Other: "Materialized subquery caches results to a temporary table, significant overhead for large result sets", } OptSelectListDependentSubqueryMessage = &i18n.Message{ ID: "OptSelectListDependentSubqueryMessage", Other: "Dependent subquery in SELECT list, executes once per outer row", } OptSelectListDependentSubqueryDetail = &i18n.Message{ ID: "OptSelectListDependentSubqueryDetail", Other: "Recommend rewriting as JOIN or extracting as independent query", } OptSubqueryToJoinMessage = &i18n.Message{ ID: "OptSubqueryToJoinMessage", Other: "IN subquery can be rewritten as JOIN (column: {{.Table}}.{{.Column}})", } OptSubqueryToJoinDetail = &i18n.Message{ ID: "OptSubqueryToJoinDetail", Other: "Rewriting IN (SELECT ...) as JOIN or EXISTS can utilize indexes for optimization", } )
var ( OptWhereHasSubqueryMessage = &i18n.Message{ ID: "OptWhereHasSubqueryMessage", Other: "Subqueries in WHERE clause are not recommended", } OptWhereHasSubqueryDetail = &i18n.Message{ ID: "OptWhereHasSubqueryDetail", Other: "Subqueries in WHERE clause may degrade performance, consider rewriting as JOIN", } OptWhereScalarSubqueryMessage = &i18n.Message{ ID: "OptWhereScalarSubqueryMessage", Other: "Scalar subquery in WHERE: ... {{.Op}} ({{.Subquery}})", } OptWhereScalarSubqueryDetail = &i18n.Message{ ID: "OptWhereScalarSubqueryDetail", Other: "Scalar subquery as comparison operand ({{.Op}}) is evaluated row-by-row. Consider: 1) rewrite as JOIN; 2) use EXISTS/IN instead; 3) cache subquery result in a variable if it returns a constant value", } OptSelectScalarSubqueryMessage = &i18n.Message{ ID: "OptSelectScalarSubqueryMessage", Other: "Scalar subquery in SELECT list: ({{.Subquery}})", } OptSelectScalarSubqueryDetail = &i18n.Message{ ID: "OptSelectScalarSubqueryDetail", Other: "Scalar subquery in SELECT is evaluated for each row of the outer query. Consider: 1) rewrite as LEFT JOIN; 2) move subquery to a CTE (WITH clause) if MySQL 8.0+", } OptMaxNestedSubqueryMessage = &i18n.Message{ ID: "OptMaxNestedSubqueryMessage", Other: "Nested subquery depth {{.Layer}} exceeds maximum {{.MaxLayer}}", } OptMaxNestedSubqueryDetail = &i18n.Message{ ID: "OptMaxNestedSubqueryDetail", Other: "Deeply nested subqueries increase query complexity and optimizer overhead, recommend flattening or rewriting as JOIN", } OptMaxSubqueryCountMessage = &i18n.Message{ ID: "OptMaxSubqueryCountMessage", Other: "Subquery count {{.Count}} exceeds maximum {{.MaxCount}}", } OptMaxSubqueryCountDetail = &i18n.Message{ ID: "OptMaxSubqueryCountDetail", Other: "Too many subqueries increase query complexity, recommend splitting or rewriting as JOIN", } OptNotInNullableColumnMessage = &i18n.Message{ ID: "OptNotInNullableColumnMessage", Other: "NOT IN subquery column {{.Column}} may contain NULL, which may cause empty result", } OptNotInNullableColumnDetail = &i18n.Message{ ID: "OptNotInNullableColumnDetail", Other: "When NOT IN subquery column contains NULL, the NOT IN condition evaluates to UNKNOWN for all rows, recommend using NOT EXISTS or adding IS NOT NULL filter", } OptSugWhereScalarSubqueryMessage = &i18n.Message{ ID: "OptSugWhereScalarSubqueryMessage", Other: "Rewrite WHERE scalar subquery as JOIN or variable", } OptSugWhereScalarSubqueryReason = &i18n.Message{ ID: "OptSugWhereScalarSubqueryReason", Other: "Scalar subquery as comparison operand ({{.Op}}) is evaluated row-by-row; rewriting as JOIN or caching into a variable can leverage indexes", } OptSugWhereScalarSubqueryActionMessage = &i18n.Message{ ID: "OptSugWhereScalarSubqueryActionMessage", Other: "Rewrite scalar subquery in WHERE as JOIN or cache in variable", } OptSugWhereScalarSubqueryActionSQL = &i18n.Message{ ID: "OptSugWhereScalarSubqueryActionSQL", Other: "-- Original: ... {{.Op}} ({{.Subquery}})\n" + "-- Option 1: Rewrite as JOIN\n" + "SELECT t.* FROM <table> t\n" + "INNER JOIN ({{.Subquery}}) AS sub ON t.<col> {{.Op}} sub.<result_col>\n" + "\n" + "-- Option 2: Cache constant subquery in variable\n" + "SET @val = ({{.Subquery}});\n" + "SELECT * FROM <table> WHERE <col> {{.Op}} @val;", } OptSugSelectScalarSubqueryMessage = &i18n.Message{ ID: "OptSugSelectScalarSubqueryMessage", Other: "Rewrite SELECT scalar subquery as LEFT JOIN", } OptSugSelectScalarSubqueryReason = &i18n.Message{ ID: "OptSugSelectScalarSubqueryReason", Other: "Scalar subquery in SELECT is evaluated per row; rewriting as LEFT JOIN or CTE reduces execution count", } OptSugSelectScalarSubqueryActionMessage = &i18n.Message{ ID: "OptSugSelectScalarSubqueryActionMessage", Other: "Rewrite scalar subquery in SELECT as LEFT JOIN or CTE", } OptSugSelectScalarSubqueryActionSQL = &i18n.Message{ ID: "OptSugSelectScalarSubqueryActionSQL", Other: "-- Original: SELECT ({{.Subquery}}) ...\n" + "-- Option 1: Rewrite as LEFT JOIN\n" + "SELECT sub.<col> FROM <table> t\n" + "LEFT JOIN (<subquery>) AS sub ON t.<key> = sub.<key>\n" + "\n" + "-- Option 2: MySQL 8.0+ use CTE\n" + "WITH sub AS ({{.Subquery}})\n" + "SELECT sub.<col> FROM <table> t\n" + "LEFT JOIN sub ON t.<key> = sub.<key>", } OptSugSelectScalarSubqueryActionMessage56 = &i18n.Message{ ID: "OptSugSelectScalarSubqueryActionMessage56", Other: "Rewrite scalar subquery in SELECT as LEFT JOIN", } OptSugSelectScalarSubqueryReason56 = &i18n.Message{ ID: "OptSugSelectScalarSubqueryReason56", Other: "Scalar subquery in SELECT is evaluated per row; rewriting as LEFT JOIN reduces execution count", } OptSugSelectScalarSubqueryActionSQL56 = &i18n.Message{ ID: "OptSugSelectScalarSubqueryActionSQL56", Other: "-- Original: SELECT ({{.Subquery}}) ...\n" + "-- Rewrite as LEFT JOIN\n" + "SELECT sub.<col> FROM <table> t\n" + "LEFT JOIN (<subquery>) AS sub ON t.<key> = sub.<key>", } )
var ( OptSugCreateIndexMessage = &i18n.Message{ ID: "OptSugCreateIndexMessage", Other: "Create index to cover query conditions", } OptSugCreateIndexActionMessage = &i18n.Message{ ID: "OptSugCreateIndexActionMessage", Other: "Create index {{.IndexName}} on table {{.Table}}", } OptSugCoveringIndexMessage = &i18n.Message{ ID: "OptSugCoveringIndexMessage", Other: "Extend index to cover SELECT columns, avoiding table lookups", } OptSugCoveringIndexReason = &i18n.Message{ ID: "OptSugCoveringIndexReason", Other: "Extend existing index {{.Key}} by adding columns {{.Columns}} to achieve covering index", } OptSugSortGroupIndexMessage = &i18n.Message{ ID: "OptSugSortGroupIndexMessage", Other: "Create composite index including sort/group columns", } OptSugSortGroupIndexReason = &i18n.Message{ ID: "OptSugSortGroupIndexReason", Other: "Composite index containing WHERE equality columns + ORDER BY/GROUP BY columns eliminates filesort", } OptSugSimpleIndexMessage = &i18n.Message{ ID: "OptSugSimpleIndexMessage", Other: "Create index for columns {{.Columns}}", } OptSugSimpleIndexReason = &i18n.Message{ ID: "OptSugSimpleIndexReason", Other: "Create index for columns lacking index to improve query performance", } OptIndexBasisTableRows = &i18n.Message{ ID: "OptIndexBasisTableRows", Other: "table rows={{.Rows}}", } OptIndexBasisColumns = &i18n.Message{ ID: "OptIndexBasisColumns", Other: "columns=[{{.Columns}}]", } OptIndexBasisColumnStats = &i18n.Message{ ID: "OptIndexBasisColumnStats", Other: "{{.Column}} (cardinality={{.Cardinality}}, selectivity={{.Selectivity}})", } OptIndexBasisSeparator = &i18n.Message{ ID: "OptIndexBasisSeparator", Other: "; ", } OptIndexBasisSummary = &i18n.Message{ ID: "OptIndexBasisSummary", Other: "table rows={{.Rows}}{{if .Columns}}; columns=[{{range $index, $column := .Columns}}{{if $index}}, {{end}}{{$column.Column}} " + "(cardinality={{$column.Cardinality}}, selectivity={{printf \"%.2f\" $column.Selectivity}}%){{end}}]{{end}}", } OptSugTooManyIndexesRisk = &i18n.Message{ ID: "OptSugTooManyIndexesRisk", Other: "Table currently has {{.Count}} indexes, adding indexes increases write overhead", } OptSugIndexReasonEq = &i18n.Message{ ID: "OptSugIndexReasonEq", Other: "{{.Column}} (equality condition, selectivity {{.Selectivity}})", } OptSugIndexReasonRange = &i18n.Message{ ID: "OptSugIndexReasonRange", Other: "{{.Column}} (range condition)", } OptSugIndexReasonOrder = &i18n.Message{ ID: "OptSugIndexReasonOrder", Other: "{{.Column}} (sort)", } OptSugIndexReasonGroup = &i18n.Message{ ID: "OptSugIndexReasonGroup", Other: "{{.Column}} (group)", } OptSugIndexReasonPushdown = &i18n.Message{ ID: "OptSugIndexReasonPushdown", Other: "{{.Column}} (pushdown condition)", } OptSugIndexReasonPrefix = &i18n.Message{ ID: "OptSugIndexReasonPrefix", Other: "Index column selection: ", } // 低效索引建议 OptSugIndexLowImprovementMessage = &i18n.Message{ ID: "OptSugIndexLowImprovementMessage", Other: "Index suggested but expected performance improvement is marginal; evaluate based on actual workload", } OptSugIndexNoImprovementMessage = &i18n.Message{ ID: "OptSugIndexNoImprovementMessage", Other: "Adding this index may have no positive effect; the estimated cost after indexing is not better than before", } OptSugIndexLowImprovementReason = &i18n.Message{ ID: "OptSugIndexLowImprovementReason", Other: "Cost improvement is only ~{{.Improvement}}%, below threshold {{.Threshold}}%", } OptSugIndexNoImprovementReason = &i18n.Message{ ID: "OptSugIndexNoImprovementReason", Other: "Estimated cost after adding index is ~{{.Improvement}}% worse than before; the index may not be beneficial", } OptSugIndexAccessMethodUnchanged = &i18n.Message{ ID: "OptSugIndexAccessMethodUnchanged", Other: "Access method remains {{.Method}} after adding index, no qualitative change", } OptSugIndexRowsNotReduced = &i18n.Message{ ID: "OptSugIndexRowsNotReduced", Other: "Row scan reduced by only ~{{.RowsReduced}}%, not significant", } OptSugIndexStillNeedsSorting = &i18n.Message{ ID: "OptSugIndexStillNeedsSorting", Other: "Filesort is still required after adding index", } )
var ( OptSugRemoveForceMessage = &i18n.Message{ ID: "OptSugRemoveForceMessage", Other: "Remove FORCE INDEX and let optimizer choose the index", } OptSugRemoveForceActionMessage = &i18n.Message{ ID: "OptSugRemoveForceActionMessage", Other: "Remove FORCE INDEX hint", } OptSugRemoveForceReason = &i18n.Message{ ID: "OptSugRemoveForceReason", Other: "FORCE INDEX({{.Indexes}}) may prevent optimizer from choosing a better index", } OptSugRemoveForceRisk = &i18n.Message{ ID: "OptSugRemoveForceRisk", Other: "After removing FORCE INDEX, optimizer may choose different indexes under certain data distributions", } OptSugRemoveIgnoreMessage = &i18n.Message{ ID: "OptSugRemoveIgnoreMessage", Other: "Remove IGNORE INDEX and allow optimizer to use the ignored index", } OptSugRemoveIgnoreActionMessage = &i18n.Message{ ID: "OptSugRemoveIgnoreActionMessage", Other: "Remove IGNORE INDEX hint", } OptSugRemoveIgnoreReason = &i18n.Message{ ID: "OptSugRemoveIgnoreReason", Other: "IGNORE INDEX({{.Indexes}}) blocks potentially effective indexes", } OptSugDeferredJoinMessage = &i18n.Message{ ID: "OptSugDeferredJoinMessage", Other: "Use deferred join to optimize large offset pagination", } OptSugDeferredJoinActionMessage = &i18n.Message{ ID: "OptSugDeferredJoinActionMessage", Other: "Rewrite as deferred join pattern", } OptSugDeferredJoinReason = &i18n.Message{ ID: "OptSugDeferredJoinReason", Other: "Subquery only scans index for primary key, reducing table lookups", } OptSugCursorPageMessage = &i18n.Message{ ID: "OptSugCursorPageMessage", Other: "Use cursor-based pagination instead of large offset", } OptSugCursorPageActionMessage = &i18n.Message{ ID: "OptSugCursorPageActionMessage", Other: "Rewrite as cursor-based pagination", } OptSugCursorPageReason = &i18n.Message{ ID: "OptSugCursorPageReason", Other: "Position by last query's last value, avoiding scanning rows before offset", } OptSugCursorPageRisk = &i18n.Message{ ID: "OptSugCursorPageRisk", Other: "Requires client to maintain cursor state, does not support page jumping", } OptSugSubqueryToJoinMessage = &i18n.Message{ ID: "OptSugSubqueryToJoinMessage", Other: "Rewrite IN subquery as JOIN", } OptSugSubqueryToJoinActionMessage = &i18n.Message{ ID: "OptSugSubqueryToJoinActionMessage", Other: "Rewrite IN subquery as JOIN or EXISTS", } OptSugSubqueryToJoinReason = &i18n.Message{ ID: "OptSugSubqueryToJoinReason", Other: "JOIN and EXISTS are usually more efficient than IN subquery and can utilize indexes", } OptSugFuncRewriteMessage = &i18n.Message{ ID: "OptSugFuncRewriteMessage", Other: "Rewrite WHERE condition to avoid using function on column {{.Column}}", } OptSugFuncRewriteActionMessage = &i18n.Message{ ID: "OptSugFuncRewriteActionMessage", Other: "Move function/operation from column side to value side", } OptSugFuncRewriteReason = &i18n.Message{ ID: "OptSugFuncRewriteReason", Other: "Moving function/operation from column side to value side allows optimizer to use indexes", } )
var ( OptWhatIfRecommendedReason = &i18n.Message{ ID: "OptWhatIfRecommendedReason", Other: "The selected design improved modeled whole-query efficiency by {{.ImprovementPercent}}%, meeting the {{.ThresholdPercent}}% recommendation threshold, so this candidate was made actionable.", } OptWhatIfBelowRecommendationThresholdReason = &i18n.Message{ ID: "OptWhatIfBelowRecommendationThresholdReason", Other: "The estimated benefit is below the recommendation target: modeled whole-query efficiency improves by about {{formatPercent .ImprovementPercent}}%, compared with the configured threshold of {{.ThresholdPercent}}%. Adding this index on its own is not recommended at this time. This is a model estimate, not measured query performance.", } OptWhatIfCandidateIndexNotUsedReason = &i18n.Message{ ID: "OptWhatIfCandidateIndexNotUsedReason", Other: "The candidate index was not used by a retained Logical IR plan under the current metadata, statistics, and model coverage, so it was not selected.", } OptWhatIfCandidateEvaluationFailedReason = &i18n.Message{ ID: "OptWhatIfCandidateEvaluationFailedReason", Other: "The candidate design could not be reliably evaluated with the available plan evidence. No conclusion about index benefit or lack of benefit is established.", } OptWhatIfCandidateEvaluationUnsupportedReason = &i18n.Message{ ID: "OptWhatIfCandidateEvaluationUnsupportedReason", Other: "The candidate design could not be reliably evaluated. Recorded model limitation: {{.Reason}}. This does not establish that the index has no benefit.", } OptWhatIfCandidateUnusedInCombinationReason = &i18n.Message{ ID: "OptWhatIfCandidateUnusedInCombinationReason", Other: "The recorded multi-candidate design did not use this index. This observation does not establish its independent benefit or lack of benefit; the combination cost must not be attributed to this index alone.", } OptWhatIfCandidateNotSelectedReason = &i18n.Message{ ID: "OptWhatIfCandidateNotSelectedReason", Other: "This candidate was not selected for the final recommendation. Its recorded design evaluation does not establish that its independent benefit is absent; inspect the exact action set before attributing a cost change.", } OptWhatIfCombinationBelowThresholdReason = &i18n.Message{ ID: "OptWhatIfCombinationBelowThresholdReason", Other: "The evaluated combination including this candidate improved modeled whole-query efficiency by {{.ImprovementPercent}}%, below the {{.ThresholdPercent}}% recommendation threshold. This is the combination benefit, not this candidate's independent benefit.", } OptWhatIfCandidateIndexNotUsedSamePlanReason = &i18n.Message{ ID: "OptWhatIfCandidateIndexNotUsedSamePlanReason", Other: "The candidate index was added to the virtual design and evaluated for the whole query, but the resulting plan is identical to the baseline (plan digest {{.PlanDigest}}) and does not use the index. Candidate cost {{.CandidateCost}}, baseline cost {{.BaselineCost}}, cost ratio {{.CostRatio}}, and modeled rows examined {{.RowsExamined}}. This recorded scenario did not select the candidate index; it does not prove that the index has no benefit outside this model and statistics.", } OptWhatIfCandidateIndexNotUsedDifferentPlanReason = &i18n.Message{ ID: "OptWhatIfCandidateIndexNotUsedDifferentPlanReason", Other: "The candidate index was added to the virtual design and evaluated for the whole query, but the resulting plan differs from the baseline (plan digest {{.PlanDigest}}) and still does not use the index. Candidate cost {{.CandidateCost}}, baseline cost {{.BaselineCost}}, cost ratio {{.CostRatio}}, and modeled rows examined {{.RowsExamined}}. This recorded scenario did not select the candidate index; the plan difference alone does not establish its independent benefit or lack of benefit.", } OptWhatIfLowCardinalityCandidateIndexNotUsedReason = &i18n.Message{ ID: "OptWhatIfLowCardinalityCandidateIndexNotUsedReason", Other: "The candidate index was not used by the retained Logical IR plan. Current statistics show low cardinality for {{.Column}} ({{.Cardinality}} distinct value(s) across {{.Rows}} rows, {{.SelectivityPercent}}% distinctness), so the model retained the baseline access path.", } OptWhatIfBaselineCostNotImprovedReason = &i18n.Message{ ID: "OptWhatIfBaselineCostNotImprovedReason", Other: "The candidate index was used by an evaluated Logical IR plan, but its modeled whole-query cost did not improve on the baseline cost, so it was not selected.", } OptMissingIndexMessage = &i18n.Message{ ID: "OptMissingIndexMessage", Other: "Conditions on table {{.Table}}{{if .Columns}} involving columns {{.Columns}}{{end}} lack a usable index search path in this analysis", } OptMissingIndexDetail = &i18n.Message{ ID: "OptMissingIndexDetail", Other: "{{.Count}} predicate group(s) lack a usable index search path. Candidate keys may also include JOIN or covering columns; review the candidate evaluations. Model benefits are not measured runtime improvements.", } OptMissingIndexBlockedMessage = &i18n.Message{ ID: "OptMissingIndexBlockedMessage", Other: "WHERE conditions on table {{.Table}} lack index coverage, but no actionable index recommendation can be generated currently", } OptMissingIndexBlockedDetail = &i18n.Message{ ID: "OptMissingIndexBlockedDetail", Other: "{{.Count}} uncovered condition group(s), related columns: {{.Columns}}; blocked reasons: {{.Reasons}}", } OptMissingIndexBlockedReasonNoCandidate = &i18n.Message{ ID: "OptMissingIndexBlockedReasonNoCandidate", Other: "No index candidate can be generated from current predicates", } OptMissingIndexBlockedReasonQuickRejected = &i18n.Message{ ID: "OptMissingIndexBlockedReasonQuickRejected", Other: "All generated candidates were rejected in quick validation (covered by existing indexes or insufficient gain)", } OptMissingIndexBlockedReasonCostEvaluate = &i18n.Message{ ID: "OptMissingIndexBlockedReasonCostEvaluate", Other: "Combined cost evaluation for generated candidates failed", } OptMissingIndexBlockedReasonNoSuggestion = &i18n.Message{ ID: "OptMissingIndexBlockedReasonNoSuggestion", Other: "Unable to build executable index suggestion from validated candidates", } OptCandidateSuggestionIncomplete = &i18n.Message{ ID: "OptCandidateSuggestionIncomplete", Other: "Candidate suggestion has no target table or executable action", } OptCandidateUnsupportedSuggestionAction = &i18n.Message{ ID: "OptCandidateUnsupportedSuggestionAction", Other: "Candidate suggestion contains no supported index or hint mutation", } OptCandidateDeduplicatedEquivalent = &i18n.Message{ ID: "OptCandidateDeduplicatedEquivalent", Other: "An equivalent candidate was already submitted to whole-query search", } OptCandidateVirtualIndexBuildFailed = &i18n.Message{ ID: "OptCandidateVirtualIndexBuildFailed", Other: "Failed to build virtual index for candidate table {{.Table}}", } OptCandidateNoIndexable = &i18n.Message{ ID: "OptCandidateNoIndexable", Other: "No supported index or hint opportunity was found", } OptCandidateRuleNotEnabled = &i18n.Message{ ID: "OptCandidateRuleNotEnabled", Other: "The table_index rule was not enabled for this analysis", } OptCandidateExistingIndexCovers = &i18n.Message{ ID: "OptCandidateExistingIndexCovers", Other: "An existing index already covers candidate columns {{.Columns}} on table {{.Table}}", } OptCandidateExistingIndexCostEffective = &i18n.Message{ ID: "OptCandidateExistingIndexCostEffective", Other: "Existing access paths on table {{.Table}} remain cost-effective; candidate index columns {{.Columns}} produce a {{.ImprovementPercent}}% modeled fast-cost change, below the {{.ThresholdPercent}}% improvement threshold", } OptCandidateRelationUnresolved = &i18n.Message{ ID: "OptCandidateRelationUnresolved", Other: "Candidate relation {{.Table}} cannot be resolved uniquely", } ID: "OptCandidateMetadataUnavailable", Other: "Metadata for candidate table {{.Table}} is unavailable", } OptCandidateColumnsInvalid = &i18n.Message{ ID: "OptCandidateColumnsInvalid", Other: "The candidate index has no valid key columns", } ID: "OptCandidateHintMutationUnavailable", Other: "The structured index-hint mutation is unavailable", } OptCandidatePrimaryKeyServes = &i18n.Message{ ID: "OptCandidatePrimaryKeyServes", Other: "The primary key already serves the indexable predicates on table {{.Table}}", } OptCandidateScanBelowThreshold = &i18n.Message{ ID: "OptCandidateScanBelowThreshold", Other: "Estimated scan rows {{.Rows}} are below the index recommendation threshold {{.Threshold}}", } OptUnsupportedColTypeMessage = &i18n.Message{ ID: "OptUnsupportedColTypeMessage", Other: "Column {{.Table}}.{{.Column}} type is {{.DataType}}, not suitable for B+Tree index", } OptLowSelectivityColMessage = &i18n.Message{ ID: "OptLowSelectivityColMessage", Other: "Column {{.Table}}.{{.Column}} has low selectivity ({{.Selectivity}}), may not benefit from indexing", } OptBetterIndexFoundMessage = &i18n.Message{ ID: "OptBetterIndexFoundMessage", Other: "Found a candidate index for table {{.Table}}; whole-query benefit is reported in what_if", } OptESRSelectedReason = &i18n.Message{ ID: "OptESRSelectedReason", Other: "ESR (Equality-Sort-Range) key ordering is a candidate design, not proof of sort elimination or index condition pushdown. Aggregate-result ordering still requires separate evaluation.", } OptERSSelectedReason = &i18n.Message{ ID: "OptERSSelectedReason", Other: "ERS (Equality-Range-Sort) key ordering prioritizes range access; actual filtering and sorting benefits require whole-query plan evaluation.", } OptHintKeepForceMessage = &i18n.Message{ ID: "OptHintKeepForceMessage", Other: "FORCE INDEX({{.Indexes}}) is using the optimal index, keep current hint", } OptHintRemoveForceNewIndexMessage = &i18n.Message{ ID: "OptHintRemoveForceNewIndexMessage", Other: "Remove FORCE INDEX({{.Indexes}}) and create a better index", } OptHintRemoveForceUseExistingMessage = &i18n.Message{ ID: "OptHintRemoveForceUseExistingMessage", Other: "Remove FORCE INDEX({{.Indexes}}), existing index {{.BetterIndex}} performs better", } OptHintRemoveIgnoreMessage = &i18n.Message{ ID: "OptHintRemoveIgnoreMessage", Other: "Remove IGNORE INDEX({{.Indexes}}), the ignored index is effective for this query", } OptHintKeepIgnoreMessage = &i18n.Message{ ID: "OptHintKeepIgnoreMessage", Other: "IGNORE INDEX({{.Indexes}}) is correct, other indexes perform better", } OptHintKeepIgnoreNewIndexMessage = &i18n.Message{ ID: "OptHintKeepIgnoreNewIndexMessage", Other: "Keep IGNORE INDEX({{.Indexes}}) and create a better index", } OptHintRemoveForceLetOptimizerMessage = &i18n.Message{ ID: "OptHintRemoveForceLetOptimizerMessage", Other: "Remove FORCE INDEX({{.Indexes}}), optimizer can choose a better plan without it", } OptSmallTableWarning = &i18n.Message{ ID: "OptSmallTableWarning", Other: "Table {{.Table}} has only {{.Rows}} rows, indexing benefit is limited", } OptNoImprovementMessage = &i18n.Message{ ID: "OptNoImprovementMessage", Other: "Existing indexes on table {{.Table}} are already optimal for this query", } OptPrefixVariantSelected = &i18n.Message{ ID: "OptPrefixVariantSelected", Other: "Prefix variant ({{.Columns}}) selected as optimal with {{.Count}} columns", } OptSugCoveringColsReason = &i18n.Message{ ID: "OptSugCoveringColsReason", Other: "Columns [{{.Columns}}] are included to enable covering index and avoid table lookups", } )
var ( OptInsertAutoIncrementMessage = &i18n.Message{ ID: "OptInsertAutoIncrementMessage", Other: "INSERT/UPDATE statement explicitly sets auto-increment column {{.Column}}", } OptInsertAutoIncrementDetail = &i18n.Message{ ID: "OptInsertAutoIncrementDetail", Other: "Auto-increment column {{.Column}} should not be explicitly set, let the database generate the value automatically", } OptInsertRequireColsMessage = &i18n.Message{ ID: "OptInsertRequireColsMessage", Other: "INSERT statement does not specify column list", } OptInsertRequireColsDetail = &i18n.Message{ ID: "OptInsertRequireColsDetail", Other: "Always specify target columns in INSERT to avoid breakage when table schema changes", } OptLockUpdateMessage = &i18n.Message{ ID: "OptLockUpdateMessage", Other: "SELECT statement uses FOR UPDATE lock", } OptLockUpdateDetail = &i18n.Message{ ID: "OptLockUpdateDetail", Other: "FOR UPDATE locks selected rows, may cause lock contention and deadlocks, use with caution", } OptUpdateDeleteNoWhereMessage = &i18n.Message{ ID: "OptUpdateDeleteNoWhereMessage", Other: "{{.StatementType}} statement has no WHERE clause", } OptUpdateDeleteNoWhereDetail = &i18n.Message{ ID: "OptUpdateDeleteNoWhereDetail", Other: "{{.StatementType}} without WHERE may affect all rows, add explicit filter conditions", } )
var ( OptSQLTooLongMessage = &i18n.Message{ ID: "OptSQLTooLongMessage", Other: "SQL length {{.Length}} exceeds maximum {{.MaxLength}}", } OptSQLTooLongDetail = &i18n.Message{ ID: "OptSQLTooLongDetail", Other: "SQL statement is too long ({{.Length}} characters), recommend splitting or simplifying the query", } OptWhereInTooManyMessage = &i18n.Message{ ID: "OptWhereInTooManyMessage", Other: "WHERE {{.Column}} IN list has {{.ColumnCount}} items, exceeding maximum {{.MaxColumnCount}}", } OptWhereInTooManyDetail = &i18n.Message{ ID: "OptWhereInTooManyDetail", Other: "Too many items in IN list may degrade performance, recommend using temporary table or batch processing", } OptWhereInNoWhereMessage = &i18n.Message{ ID: "OptWhereInNoWhereMessage", Other: "IN subquery has no WHERE condition", } OptWhereInNoWhereDetail = &i18n.Message{ ID: "OptWhereInNoWhereDetail", Other: "IN subquery without WHERE condition may scan the entire table, recommend adding filter conditions", } OptLimitExceedMessage = &i18n.Message{ ID: "OptLimitExceedMessage", Other: "LIMIT value {{.LimitValue}} exceeds maximum {{.MaxLimitValue}}", } OptLimitExceedDetail = &i18n.Message{ ID: "OptLimitExceedDetail", Other: "Fetching too many rows at once may cause excessive memory usage and network overhead", } OptLimitNoUseOffsetMessage = &i18n.Message{ ID: "OptLimitNoUseOffsetMessage", Other: "LIMIT with OFFSET is not recommended, consider cursor-based pagination", } OptLimitNoUseOffsetDetail = &i18n.Message{ ID: "OptLimitNoUseOffsetDetail", Other: "OFFSET-based pagination scans and discards rows before the offset, performance degrades as offset grows", } OptLimitOffsetExceedMessage = &i18n.Message{ ID: "OptLimitOffsetExceedMessage", Other: "LIMIT OFFSET value {{.OffsetValue}} exceeds maximum {{.MaxOffsetValue}}", } OptLimitOffsetExceedDetail = &i18n.Message{ ID: "OptLimitOffsetExceedDetail", Other: "Large OFFSET scans and discards many rows, recommend using cursor-based pagination or deferred join", } OptForbiddenFuncMessage = &i18n.Message{ ID: "OptForbiddenFuncMessage", Other: "Function {{.Function}} is forbidden", } OptForbiddenFuncDetail = &i18n.Message{ ID: "OptForbiddenFuncDetail", Other: "Function {{.Function}} is not allowed by audit rules, consider using an alternative", } OptValueStringSpaceMessage = &i18n.Message{ ID: "OptValueStringSpaceMessage", Other: "String value has leading or trailing spaces: '{{.Value}}'", } OptValueStringSpaceDetail = &i18n.Message{ ID: "OptValueStringSpaceDetail", Other: "String value with leading/trailing spaces may cause unexpected matching results, recommend using TRIM() or removing spaces", } )
var ( OptCostTooManyIndexCols = &i18n.Message{ ID: "OptCostTooManyIndexCols", Other: "Too many index columns ({{.Count}} columns), may impact write performance", } OptCostTooManyIndexes = &i18n.Message{ ID: "OptCostTooManyIndexes", Other: "Table already has {{.Count}} indexes, add new indexes with caution", } )
var ( OptWhereNoWhereMessage = &i18n.Message{ ID: "OptWhereNoWhereMessage", Other: "SELECT statement has no WHERE clause", } OptWhereNoWhereDetail = &i18n.Message{ ID: "OptWhereNoWhereDetail", Other: "SELECT without WHERE clause will scan the entire table, recommend adding filter conditions", } OptWhereNoWhereLargeTableDetail = &i18n.Message{ ID: "OptWhereNoWhereLargeTableDetail", Other: "Table {{.Table}} has {{.Rows}} rows, SELECT without WHERE will cause full table scan with significant performance impact", } OptWhereNoWhereSmallTableDetail = &i18n.Message{ ID: "OptWhereNoWhereSmallTableDetail", Other: "Table {{.Table}} has {{.Rows}} rows, full table scan impact is minor but adding WHERE is recommended", } OptWhereLikeFuzzyMatchMessage = &i18n.Message{ ID: "OptWhereLikeFuzzyMatchMessage", Other: "LIKE pattern starts with wildcard character, cannot use index", } OptWhereLikeFuzzyMatchDetail = &i18n.Message{ ID: "OptWhereLikeFuzzyMatchDetail", Other: "LIKE '%...' or LIKE '_...' pattern invalidates the index, consider using fulltext index or rewriting the query", } OptWhereLikeNoWildcardMessage = &i18n.Message{ ID: "OptWhereLikeNoWildcardMessage", Other: "LIKE pattern has no wildcard character, consider using = operator", } OptWhereLikeNoWildcardDetail = &i18n.Message{ ID: "OptWhereLikeNoWildcardDetail", Other: "LIKE pattern without wildcard (% or _) is equivalent to = comparison, recommend using = for clarity and performance", } OptWhereCompareNullMessage = &i18n.Message{ ID: "OptWhereCompareNullMessage", Other: "Comparing column with NULL using = or != operator", } OptWhereCompareNullDetail = &i18n.Message{ ID: "OptWhereCompareNullDetail", Other: "NULL comparison with = or != always returns NULL, use IS NULL or IS NOT NULL instead", } OptWhereOrDiffTableMessage = &i18n.Message{ ID: "OptWhereOrDiffTableMessage", Other: "OR condition branches reference different tables", } OptWhereOrDiffTableDetail = &i18n.Message{ ID: "OptWhereOrDiffTableDetail", Other: "OR condition with columns from different tables may prevent index usage and cause full table scan", } OptWhereOpOnColumnMessage = &i18n.Message{ ID: "OptWhereOpOnColumnMessage", Other: "Function or operation on WHERE condition column {{.Column}}", } OptWhereOpOnColumnDetail = &i18n.Message{ ID: "OptWhereOpOnColumnDetail", Other: "Function or arithmetic operation on column {{.Column}} in WHERE condition may prevent index usage, recommend moving operation to value side", } OptWhereIndexInvalidNotMessage = &i18n.Message{ ID: "OptWhereIndexInvalidNotMessage", Other: "NOT operator used in WHERE condition, may prevent index usage", } OptWhereIndexInvalidNotDetail = &i18n.Message{ ID: "OptWhereIndexInvalidNotDetail", Other: "NOT BETWEEN, NOT IN, NOT LIKE, NOT EXISTS, NOT REGEXP may prevent the optimizer from using indexes", } OptWhereIndexInvalidOpMessage = &i18n.Message{ ID: "OptWhereIndexInvalidOpMessage", Other: "Function or operation on indexed column {{.Column}} will invalidate the index", } OptWhereIndexInvalidOpDetail = &i18n.Message{ ID: "OptWhereIndexInvalidOpDetail", Other: "Column {{.Column}} has index, but function or arithmetic operation on it prevents index usage", } OptWhereBlockedExistingIndexDetail = &i18n.Message{ ID: "OptWhereBlockedExistingIndexDetail", Other: "`{{.Expression}}` prevents `{{.Index}}` from serving this condition", } OptWhereServedIndexDetail = &i18n.Message{ ID: "OptWhereServedIndexDetail", Other: "Existing index `{{.Index}}` already serves this condition; the expression remains a residual filter", } OptWhereCheckHasIndexMessage = &i18n.Message{ ID: "OptWhereCheckHasIndexMessage", Other: "WHERE conditions on table {{.Table}} do not hit any index, columns without index: {{.Columns}}", } OptWhereCheckHasIndexDetail = &i18n.Message{ ID: "OptWhereCheckHasIndexDetail", Other: "No index column found in WHERE conditions for table {{.Table}}, columns without index: {{.Columns}}, may cause full table scan, recommend creating appropriate index", } OptWhereCheckIndexValTypeMessage = &i18n.Message{ ID: "OptWhereCheckIndexValTypeMessage", Other: "Index column {{.ColumnName}} (type {{.ColumnType}}) compared with mismatched value type {{.ValueType}}", } OptWhereCheckIndexValTypeDetail = &i18n.Message{ ID: "OptWhereCheckIndexValTypeDetail", Other: "Type mismatch between column {{.ColumnName}} and comparison value may cause implicit conversion and invalidate the index", } OptWhereCombineIndexLeftMessage = &i18n.Message{ ID: "OptWhereCombineIndexLeftMessage", Other: "Composite index leftmost prefix column not used in WHERE condition", } OptWhereCombineIndexLeftDetail = &i18n.Message{ ID: "OptWhereCombineIndexLeftDetail", Other: "Composite index requires the leftmost column to be present in WHERE condition to be effective", } OptWhereCombineIndexLeftNotEqMessage = &i18n.Message{ ID: "OptWhereCombineIndexLeftNotEqMessage", Other: "Composite index leftmost prefix column uses inequality condition, index effectiveness is limited", } OptWhereCombineIndexLeftNotEqDetail = &i18n.Message{ ID: "OptWhereCombineIndexLeftNotEqDetail", Other: "Composite index leftmost column with inequality (!=, NOT, LIKE '%...') limits index range scan effectiveness", } OptCTESingleRefMaterializeMessage = &i18n.Message{ ID: "OptCTESingleRefMaterializeMessage", Other: "CTE '{{.CTEName}}' is referenced only once but materialized; consider rewriting as a derived table (subquery) to avoid materialization overhead", } OptCTESingleRefMaterializeDetail = &i18n.Message{ ID: "OptCTESingleRefMaterializeDetail", Other: "CTE '{{.CTEName}}' is referenced only once in the query. MySQL materializes CTEs into temporary tables by default. For single-use CTEs, using a derived table (inline subquery) allows the optimizer to merge it into the outer query, potentially improving performance", } OptCTERecursiveNoLimitMessage = &i18n.Message{ ID: "OptCTERecursiveNoLimitMessage", Other: "Recursive CTE '{{.CTEName}}' has no LIMIT or termination depth control, risk of infinite recursion", } OptCTERecursiveNoLimitDetail = &i18n.Message{ ID: "OptCTERecursiveNoLimitDetail", Other: "Recursive CTE '{{.CTEName}}' does not have a LIMIT clause or explicit depth limit in the recursive member's WHERE condition. This may cause infinite recursion and excessive resource consumption. Consider adding a depth counter column with a WHERE limit, or set cte_max_recursion_depth", } )
var ( OptWhatIfCardinalityHeuristic = &goi18n.Message{ ID: "OptWhatIfCardinalityHeuristic", Other: "cardinality confidence is based on table statistics and heuristic predicate estimates", } OptWhatIfTableCardinalityHeuristic = &goi18n.Message{ ID: "OptWhatIfTableCardinalityHeuristic", Other: "table {{.Table}} cardinality uses heuristic predicate estimates", } OptWhatIfNonEqualityJoinSelectivity = &goi18n.Message{ ID: "OptWhatIfNonEqualityJoinSelectivity", Other: "non-equality JOIN predicate {{.Predicate}} uses heuristic selectivity", } OptWhatIfPredicateDNFLimit = &goi18n.Message{ ID: "OptWhatIfPredicateDNFLimit", Other: "predicate DNF exceeded enumeration limits; predicate index paths were skipped conservatively", } OptWhatIfRecursiveCTENoBound = &goi18n.Message{ ID: "OptWhatIfRecursiveCTENoBound", Other: "recursive CTE has no statically provable termination bound; cost is capped at cte_max_recursion_depth={{.Depth}}", } OptWhatIfRecursiveCTECapped = &goi18n.Message{ ID: "OptWhatIfRecursiveCTECapped", Other: "estimated recursion exceeds cte_max_recursion_depth={{.Depth}} and was capped", } OptWhatIfRecursiveCTERowCap = &goi18n.Message{ ID: "OptWhatIfRecursiveCTERowCap", Other: "recursive CTE cardinality reached the safety cap of {{.Rows}} rows", } OptWhatIfRecursiveMemberHeuristic = &goi18n.Message{ ID: "OptWhatIfRecursiveMemberHeuristic", Other: "recursive member cardinality uses a heuristic growth estimate", } OptWhatIfRecursiveNonEqualityJoin = &goi18n.Message{ ID: "OptWhatIfRecursiveNonEqualityJoin", Other: "recursive non-equality JOIN predicate {{.Predicate}} uses heuristic selectivity", } OptWhatIfPartitionPruningHeuristic = &goi18n.Message{ ID: "OptWhatIfPartitionPruningHeuristic", Other: "partition pruning uses information_schema boundary and cardinality estimates", } OptWhatIfPartitionCardinalityEstimate = &goi18n.Message{ ID: "OptWhatIfPartitionCardinalityEstimate", Other: "partition cardinalities come from information_schema estimates", } OptWhatIfPartitionNativeSet = &goi18n.Message{ ID: "OptWhatIfPartitionNativeSet", Other: "partition pruning reuses the exact native EXPLAIN partition set", } OptWhatIfCartesianJoinHeuristic = &goi18n.Message{ ID: "OptWhatIfCartesianJoinHeuristic", Other: "cartesian JOIN cardinality uses heuristic estimate", } OptWhatIfNotInNullDiscard = &goi18n.Message{ ID: "OptWhatIfNotInNullDiscard", Other: "NOT IN subquery output is estimated to contain NULL; the model predicts that WHERE discards all UNKNOWN results", } OptWhatIfExistsSession = &goi18n.Message{ ID: "OptWhatIfExistsSession", Other: "Target-session semijoin settings are missing or inconsistent. EXISTS comparisons include only strategies with confirmed eligibility.", } OptWhatIfExistsPrefixEstimate = &goi18n.Message{ ID: "OptWhatIfExistsPrefixEstimate", Other: "ordered EXISTS estimates an unmeasured outer prefix from the complete census, assuming uniformly distributed hits within the remaining interval", } OptWhatIfExistsLookupEstimate = &goi18n.Message{ ID: "OptWhatIfExistsLookupEstimate", Other: "ordered EXISTS inner lookup work is estimated because the access path does not establish the observed witness order", } OptWhatIfWeedoutRanking = &goi18n.Message{ ID: "OptWhatIfWeedoutRanking", Other: "A competing Duplicate Weedout could cost less within its temporary-table cost interval. Ranking uses the conservative upper estimate.", } OptWhatIfWeedoutCostInterval = &goi18n.Message{ ID: "OptWhatIfWeedoutCostInterval", Other: "Duplicate Weedout is priced at the upper end of its temporary-table cost interval. The session budget, key width or distinct population is uncertain.", } OptWhatIfExistsLookupAverage = &goi18n.Message{ ID: "OptWhatIfExistsLookupAverage", Other: "ordered EXISTS uses the known outer rank and estimates its inner work from the full census", } OptWhatIfExistsBooleanContext = &goi18n.Message{ ID: "OptWhatIfExistsBooleanContext", Other: "whole-query work cannot combine an EXISTS result inside this Boolean expression", } OptWhatIfExistsProbeDepthTruncated = &goi18n.Message{ ID: "OptWhatIfExistsProbeDepthTruncated", Other: "parameterized EXISTS probe search truncated at nesting depth budget", } OptWhatIfMaterializedCensus = &goi18n.Message{ ID: "OptWhatIfMaterializedCensus", Other: "materialized membership uses observed build counts and in-memory temporary key costs", } OptWhatIfParameterizedExistsIndependent = &goi18n.Message{ ID: "OptWhatIfParameterizedExistsIndependent", Other: "ordered EXISTS prefix work assumes independent matches along the driving key; skew and joint probe selectivity are uncalibrated", } OptWhatIfNestedExistsDriverBuild = &goi18n.Message{ ID: "OptWhatIfNestedExistsDriverBuild", Other: "nested EXISTS driver bounds leaf probes using same-snapshot build counts and estimates outer lookups separately", } OptWhatIfNestedExistsDriverObserved = &goi18n.Message{ ID: "OptWhatIfNestedExistsDriverObserved", Other: "nested EXISTS driver estimates input work from marginal filter frequencies and uses the observed count of surviving outer identities", } OptWhatIfNestedExistsDriverMarginal = &goi18n.Message{ ID: "OptWhatIfNestedExistsDriverMarginal", Other: "nested EXISTS driver uses marginal filter frequencies and an upper estimate of distinct surviving outer rows", } OptWhatIfConstantExistsBooleanContext = &goi18n.Message{ ID: "OptWhatIfConstantExistsBooleanContext", Other: "whole-query work does not model a constant EXISTS inside this Boolean expression", } OptWhatIfExistsBoundLimitOffset = &goi18n.Message{ ID: "OptWhatIfExistsBoundLimitOffset", Other: "whole-query EXISTS requires bound LIMIT and OFFSET values for its input binding", } OptWhatIfExistsPostOffsetWitness = &goi18n.Message{ ID: "OptWhatIfExistsPostOffsetWitness", Other: "whole-query EXISTS requires the post-OFFSET witness count for its input binding", } OptWhatIfExistsTablelessWhere = &goi18n.Message{ ID: "OptWhatIfExistsTablelessWhere", Other: "whole-query EXISTS cannot evaluate this tableless WHERE predicate", } OptWhatIfExistsSetOperation = &goi18n.Message{ ID: "OptWhatIfExistsSetOperation", Other: "whole-query work cannot bind the set operation inside this EXISTS predicate", } OptWhatIfOrderByIndexOrderEvidence = &goi18n.Message{ ID: "OptWhatIfOrderByIndexOrderEvidence", Other: "whole-query ORDER BY comparison requires existing index key directions or prefix lengths and an ordered access method", } OptWhatIfSelectListProbeSingleTable = &goi18n.Message{ ID: "OptWhatIfSelectListProbeSingleTable", Other: "whole-query SELECT-list probes require one physical inner table and equality correlation", } OptWhatIfSelectListProbeInnerModifiers = &goi18n.Message{ ID: "OptWhatIfSelectListProbeInnerModifiers", Other: "whole-query SELECT-list probes do not yet model grouped, distinct, window or found-rows inner queries", } OptWhatIfSelectListProbeLimitOffset = &goi18n.Message{ ID: "OptWhatIfSelectListProbeLimitOffset", Other: "whole-query SELECT-list probes require a known inner LIMIT and OFFSET", } OptWhatIfSelectListProbeDirectProjection = &goi18n.Message{ ID: "OptWhatIfSelectListProbeDirectProjection", Other: "whole-query SELECT-list probes require direct scalar projections", } OptWhatIfSelectListProbeOuterModifiers = &goi18n.Message{ ID: "OptWhatIfSelectListProbeOuterModifiers", Other: "whole-query work does not yet model SELECT-list probes with outer grouping, deduplication or windows", } OptWhatIfSelectListProbeOrderInput = &goi18n.Message{ ID: "OptWhatIfSelectListProbeOrderInput", Other: "whole-query SELECT-list probes require outer ORDER BY on input columns", } OptWhatIfNotInNullable = &goi18n.Message{ ID: "OptWhatIfNotInNullable", Other: "NOT IN subquery output is nullable; result cardinality depends on whether the filtered subquery contains NULL", } OptWhatIfNotInOuterNullable = &goi18n.Message{ ID: "OptWhatIfNotInOuterNullable", Other: "NOT IN outer operand is nullable; rows with NULL outer values evaluate to UNKNOWN and are discarded by WHERE", } OptWhatIfDMLWriteHeuristic = &goi18n.Message{ ID: "OptWhatIfDMLWriteHeuristic", Other: "DML write cost uses page, index-height, locking, and logging heuristics", } OptWhatIfMultiTableDMLRows = &goi18n.Message{ ID: "OptWhatIfMultiTableDMLRows", Other: "multi-table DML affected rows are estimated as distinct target rows bounded by join output", } ID: "OptWhatIfColumnStatsUnavailable", Other: "statistics for {{.Table}}.{{.Column}} are unavailable", } OptWhatIfColumnNDVFallback = &goi18n.Message{ ID: "OptWhatIfColumnNDVFallback", Other: "NDV for {{.Table}}.{{.Column}} uses sqrt(rows) fallback", } OptWhatIfJoinNoParameterizedPath = &goi18n.Message{ ID: "OptWhatIfJoinNoParameterizedPath", Other: "JOIN inner table {{.Table}} has no parameterized index path", } OptWhatIfJoinNoEqualityLookup = &goi18n.Message{ ID: "OptWhatIfJoinNoEqualityLookup", Other: "JOIN inner table {{.Table}} has no equality predicate for parameterized lookup", } OptWhatIfBaselineWorseRetained = &goi18n.Message{ ID: "OptWhatIfBaselineWorseRetained", Other: "candidate search returned a plan worse than baseline; baseline plan was retained", } OptWhatIfEnumerationStopped = &goi18n.Message{ ID: "OptWhatIfEnumerationStopped", Other: "candidate enumeration stopped at {{.Limit}} physical designs", } OptWhatIfGreedySearch = &goi18n.Message{ ID: "OptWhatIfGreedySearch", Other: "candidate count exceeded exhaustive-search limit; marginal-gain greedy search was used", } OptWhatIfCandidateRelationSkipped = &goi18n.Message{ ID: "OptWhatIfCandidateRelationSkipped", Other: "candidate {{.Candidate}} skipped: relation {{.Database}}.{{.Table}} is unresolved or ambiguous", } OptWhatIfCandidateMetadataSkipped = &goi18n.Message{ ID: "OptWhatIfCandidateMetadataSkipped", Other: "candidate {{.Candidate}} skipped: metadata for table {{.Table}} is unavailable", } OptWhatIfCandidateHintSkipped = &goi18n.Message{ ID: "OptWhatIfCandidateHintSkipped", Other: "candidate {{.Candidate}} skipped: structured hint mutation is unavailable", } OptWhatIfCandidateSkipped = &goi18n.Message{ ID: "OptWhatIfCandidateSkipped", Other: "candidate {{.Candidate}} skipped: {{.Detail}}", } ID: "OptWhatIfNativeBaselineUnavailable", Other: "native MySQL baseline is unavailable; costs are reported in internal model units", } ID: "OptWhatIfJoinBaselineStructureUnavailable", Other: "native EXPLAIN structure is unavailable for JOIN baseline validation; costs are reported in internal model units", } OptWhatIfBaselineAccessMethodDiffers = &goi18n.Message{ ID: "OptWhatIfBaselineAccessMethodDiffers", Other: "internal baseline access method {{.Internal}} differs from MySQL {{.MySQL}}", } OptWhatIfBaselineIndexDiffers = &goi18n.Message{ ID: "OptWhatIfBaselineIndexDiffers", Other: "internal baseline index {{.Internal}} differs from MySQL {{.MySQL}}", } OptWhatIfBaselineRowsDiffer = &goi18n.Message{ ID: "OptWhatIfBaselineRowsDiffer", Other: "internal baseline rows estimate {{.Internal}} differs materially from MySQL {{.MySQL}}", } ID: "OptWhatIfStructuredAccessesUnavailable", Other: "structured baseline table accesses are unavailable", } OptWhatIfBaselineAccessCountDiffers = &goi18n.Message{ ID: "OptWhatIfBaselineAccessCountDiffers", Other: "internal baseline has {{.Internal}} table accesses while MySQL has {{.MySQL}}", } OptWhatIfBaselineJoinOrderDiffers = &goi18n.Message{ ID: "OptWhatIfBaselineJoinOrderDiffers", Other: "baseline join order differs at position {{.Position}}: internal={{.Internal}} MySQL={{.MySQL}}", } OptWhatIfBaselineTableAccessDiffers = &goi18n.Message{ ID: "OptWhatIfBaselineTableAccessDiffers", Other: "baseline access method differs for table {{.Table}}: internal={{.Internal}} MySQL={{.MySQL}}", } OptWhatIfBaselineTableIndexDiffers = &goi18n.Message{ ID: "OptWhatIfBaselineTableIndexDiffers", Other: "baseline index differs for table {{.Table}}: internal={{.Internal}} MySQL={{.MySQL}}", } OptWhatIfBaselineTableRowsDiffer = &goi18n.Message{ ID: "OptWhatIfBaselineTableRowsDiffer", Other: "baseline rows estimate differs for table {{.Table}}: internal={{.Internal}} MySQL={{.MySQL}}", } OptWhatIfBaselineJoinAlgorithmsDiffer = &goi18n.Message{ ID: "OptWhatIfBaselineJoinAlgorithmsDiffer", Other: "baseline JOIN algorithms differ: internal={{.Internal}} MySQL={{.MySQL}}", } OptWhatIfExtendedAccessUnmatched = &goi18n.Message{ ID: "OptWhatIfExtendedAccessUnmatched", Other: "extended baseline access could not be matched: table={{.Table}} method={{.Method}} indexes={{.Indexes}}", } OptWhatIfExtendedRowsDiffer = &goi18n.Message{ ID: "OptWhatIfExtendedRowsDiffer", Other: "extended baseline rows differ for table {{.Table}}: internal={{.Internal}} MySQL={{.MySQL}}", } OptWhatIfBaselineOperatorMissing = &goi18n.Message{ ID: "OptWhatIfBaselineOperatorMissing", Other: "internal baseline contains {{.Operator}} but native EXPLAIN does not", } OptWhatIfBaselineUpdateShape = &goi18n.Message{ ID: "OptWhatIfBaselineUpdateShape", Other: "native statement is UPDATE but internal baseline root differs", } OptWhatIfBaselineDeleteShape = &goi18n.Message{ ID: "OptWhatIfBaselineDeleteShape", Other: "native statement is DELETE but internal baseline root differs", } OptWhatIfBaselineInsertShape = &goi18n.Message{ ID: "OptWhatIfBaselineInsertShape", Other: "native statement is INSERT/REPLACE but internal baseline root differs", } OptWhatIfUnsupportedInnerJoinEmpty = &goi18n.Message{ ID: "OptWhatIfUnsupportedInnerJoinEmpty", Other: "INNER JOIN graph is empty", } OptWhatIfUnsupportedEstimateTable = &goi18n.Message{ ID: "OptWhatIfUnsupportedEstimateTable", Other: "could not estimate table {{.Table}}", } OptWhatIfUnsupportedInnerJoinPlan = &goi18n.Message{ ID: "OptWhatIfUnsupportedInnerJoinPlan", Other: "no connected INNER JOIN plan could be constructed", } OptWhatIfUnsupportedCTEDefinition = &goi18n.Message{ ID: "OptWhatIfUnsupportedCTEDefinition", Other: "CTE definition is unavailable", } OptWhatIfUnsupportedCTEOptimize = &goi18n.Message{ ID: "OptWhatIfUnsupportedCTEOptimize", Other: "CTE {{.Name}} definition could not be optimized", } OptWhatIfUnsupportedRecursiveCTE = &goi18n.Message{ ID: "OptWhatIfUnsupportedRecursiveCTE", Other: "recursive CTE definition is unavailable", } OptWhatIfUnsupportedRecursiveAnchor = &goi18n.Message{ ID: "OptWhatIfUnsupportedRecursiveAnchor", Other: "recursive CTE anchor member {{.Member}} could not be optimized", } OptWhatIfUnsupportedRecursiveMember = &goi18n.Message{ ID: "OptWhatIfUnsupportedRecursiveMember", Other: "recursive CTE member {{.Member}} could not be optimized", } OptWhatIfUnsupportedDMLPlan = &goi18n.Message{ ID: "OptWhatIfUnsupportedDMLPlan", Other: "DML logical plan is incomplete", } OptWhatIfUnsupportedDMLRead = &goi18n.Message{ ID: "OptWhatIfUnsupportedDMLRead", Other: "DML read plan is unavailable", } OptWhatIfUnsupportedDMLStats = &goi18n.Message{ ID: "OptWhatIfUnsupportedDMLStats", Other: "target table statistics are unavailable for {{.Table}}", } OptWhatIfUnsupportedSetBranches = &goi18n.Message{ ID: "OptWhatIfUnsupportedSetBranches", Other: "set operation branches are incomplete", } OptWhatIfUnsupportedSetBranch = &goi18n.Message{ ID: "OptWhatIfUnsupportedSetBranch", Other: "set operation branch {{.Branch}} could not be optimized", } OptWhatIfUnsupportedDerived = &goi18n.Message{ ID: "OptWhatIfUnsupportedDerived", Other: "derived relation is unavailable", } OptWhatIfUnsupportedDerivedOptimize = &goi18n.Message{ ID: "OptWhatIfUnsupportedDerivedOptimize", Other: "derived relation could not be optimized", } OptWhatIfUnsupportedTableStats = &goi18n.Message{ ID: "OptWhatIfUnsupportedTableStats", Other: "table statistics are unavailable", } OptWhatIfUnsupportedAccessPath = &goi18n.Message{ ID: "OptWhatIfUnsupportedAccessPath", Other: "cost model could not enumerate an access path", } OptWhatIfUnsupportedTablePlan = &goi18n.Message{ ID: "OptWhatIfUnsupportedTablePlan", Other: "cost model could not build a complete table plan", } OptWhatIfUnsupportedOuterJoin = &goi18n.Message{ ID: "OptWhatIfUnsupportedOuterJoin", Other: "OUTER JOIN structure is incomplete", } OptWhatIfUnsupportedOuterJoinTree = &goi18n.Message{ ID: "OptWhatIfUnsupportedOuterJoinTree", Other: "OUTER JOIN tree could not be planned", } OptWhatIfUnsupportedOuterJoinStats = &goi18n.Message{ ID: "OptWhatIfUnsupportedOuterJoinStats", Other: "OUTER JOIN relation statistics are unavailable", } OptWhatIfPartitionAbsent = &goi18n.Message{ ID: "OptWhatIfPartitionAbsent", Other: "partition {{.Partition}} is absent from metadata", } OptWhatIfPartitionMetadataRequired = &goi18n.Message{ ID: "OptWhatIfPartitionMetadataRequired", Other: "explicit partition selection requires partition metadata", } OptWhatIfPartitionNoneSelected = &goi18n.Message{ ID: "OptWhatIfPartitionNoneSelected", Other: "partition pruning selected no known partition", } ID: "OptWhatIfPartitionRowsUnavailable", Other: "partition row estimates are unavailable", } OptWhatIfCartesianJoinUnsupported = &goi18n.Message{ ID: "OptWhatIfCartesianJoinUnsupported", Other: "cartesian JOIN without an ON predicate is not supported", } OptWhatIfDisconnectedJoinUnsupported = &goi18n.Message{ ID: "OptWhatIfDisconnectedJoinUnsupported", Other: "disconnected JOIN graph and cartesian products are not supported", } OptWhatIfNoJoinPredicates = &goi18n.Message{ ID: "OptWhatIfNoJoinPredicates", Other: "INNER JOIN graph has no supported join predicates", } OptWhatIfDerivedNotSupported = &goi18n.Message{ ID: "OptWhatIfDerivedNotSupported", Other: "derived tables, set operations, and recursive queries are not supported yet", } OptWhatIfStatementUnsupported = &goi18n.Message{ ID: "OptWhatIfStatementUnsupported", Other: "statement type {{.Type}} is not supported by the internal what-if model", } OptWhatIfConnectedStatementUnsupported = &goi18n.Message{ ID: "OptWhatIfConnectedStatementUnsupported", Other: "statement type {{.Type}} does not support connected whole-query what-if analysis", } OptWhatIfJoinRelationCount = &goi18n.Message{ ID: "OptWhatIfJoinRelationCount", Other: "INNER JOIN phase supports two to five physical/CTE relations, got {{.Count}}", } OptWhatIfInnerHashWork = &goi18n.Message{ ID: "OptWhatIfInnerHashWork", Other: "inner equijoin hash work assumes memory residency; hash coefficients, collisions and spill are not calibrated to runtime", } OptWhatIfWholeQueryCoefficients = &goi18n.Message{ ID: "OptWhatIfWholeQueryCoefficients", Other: "whole-query work uses existing operator coefficients; added materialization, deduplication and aggregation work is not calibrated to wall time", } OptWhatIfMarginalSelectivity = &goi18n.Message{ ID: "OptWhatIfMarginalSelectivity", Other: "selectivity uses available marginal statistics; uniformity, predicate independence, range and overlap fallbacks do not represent observed joint statistics", } OptWhatIfDerivedMaterialization = &goi18n.Message{ ID: "OptWhatIfDerivedMaterialization", Other: "derived materialization assumes memory residency; spill and row-width costs are not calibrated", } OptWhatIfHavingCardinality = &goi18n.Message{ ID: "OptWhatIfHavingCardinality", Other: "whole-query work does not yet model HAVING cardinality", } OptWhatIfAggregateOrderAlias = &goi18n.Message{ ID: "OptWhatIfAggregateOrderAlias", Other: "whole-query work requires aggregate ORDER BY to reference a projected alias", } OptWhatIfAggregateProjection = &goi18n.Message{ ID: "OptWhatIfAggregateProjection", Other: "whole-query work currently requires direct aggregate projections", } OptWhatIfDistinctAggregate = &goi18n.Message{ ID: "OptWhatIfDistinctAggregate", Other: "whole-query work does not yet model DISTINCT aggregate state", } OptWhatIfAggregateFunction = &goi18n.Message{ ID: "OptWhatIfAggregateFunction", Other: "whole-query work does not yet model this aggregate function", } OptWhatIfRepeatedDerivedJoin = &goi18n.Message{ ID: "OptWhatIfRepeatedDerivedJoin", Other: "whole-query work does not yet model repeated derived JOIN materialization", } OptWhatIfInvalidEstimateOrCardinality = &goi18n.Message{ ID: "OptWhatIfInvalidEstimateOrCardinality", Other: "invalid estimates or logical output cardinality changed", } OptWhatIfCandidateSearchIncomplete = &goi18n.Message{ ID: "OptWhatIfCandidateSearchIncomplete", Other: "candidate search incomplete: budget {{.Budget}} or context cancellation", } OptWhatIfPlanEnumerationBudgetReached = &goi18n.Message{ ID: "OptWhatIfPlanEnumerationBudgetReached", Other: "one or more candidate plans reached an internal plan-enumeration budget", } OptWhatIfProducerWorkExcluded = &goi18n.Message{ ID: "OptWhatIfProducerWorkExcluded", Other: "producer work is excluded from the model root; whole-query recommendation comparison is unavailable", } OptWhatIfUnsupportedSubqueryOptimize = &goi18n.Message{ ID: "OptWhatIfUnsupportedSubqueryOptimize", Other: "{{.Location}} subquery could not be optimized", } OptWhatIfPartitionPredicateUnmapped = &goi18n.Message{ ID: "OptWhatIfPartitionPredicateUnmapped", Other: "partition predicate could not be safely mapped to metadata boundaries", } OptWhatIfDiagnosticLiteral = &goi18n.Message{ ID: "OptWhatIfDiagnosticLiteral", Other: "{{.Detail}}", } )
What-if diagnostics stay English inside the cost model. These templates are the optimizer-owned localization contract for the same text.
var OptCandidateSearchIncomplete = &i18n.Message{ID: "OptCandidateSearchIncomplete", Other: "This candidate was not evaluated within the available search budget or before cancellation. Its benefit is unknown, not zero."}
var OptCandidateSuperseded = &i18n.Message{ID: "OptCandidateSuperseded", Other: "This candidate has an independently evaluated model benefit, but a cheaper evaluated design was selected. It is superseded, not proven ineffective."}
var ReportIndexImprovementCombined = &i18n.Message{ID: "report.mysql.index_design_improvement.combined", Other: "Compared with the current index design and plan constraints, the selected design involving {{.TargetSummary}} reduces the estimated whole-query model cost from {{.BaselineCost}} to {{.CandidateCost}} ({{.ImprovementPercent}}% lower), meeting the recorded model efficiency-gain threshold of {{.ThresholdPercent}}%. This estimate applies to the complete recommended action set, including any recorded hint changes; it is not the independent benefit of any single index."}
ReportIndexImprovementCombined attributes benefit to the complete selected design.
var ReportIndexImprovementSingle = &i18n.Message{ID: "report.mysql.index_design_improvement.single", Other: "Compared with the current index design, the internal cost model estimates that the recommended index {{.IndexDefinition}} on {{.QualifiedTable}} reduces the whole-query modeled cost from {{.BaselineCost}} to {{.CandidateCost}} ({{.ImprovementPercent}}% lower), meeting the recorded model efficiency-gain threshold of {{.ThresholdPercent}}%. The alternative is used by the selected model plan. This indicates index optimization potential for this SQL; it does not establish that the existing indexes are invalid."}
ReportIndexImprovementSingle qualifies the estimate and the recorded policy metric.
var ReportIndexImprovementTitle = &i18n.Message{ID: "report.mysql.index_design_improvement.title", Other: "Better index design found"}
ReportIndexImprovementTitle names an evaluation-derived, model-only finding.
var ReportIndexImprovementValidation = &i18n.Message{ID: "report.mysql.index_design_improvement.validation", Other: "This is an internal-model estimate, not a measured runtime improvement or a guarantee that MySQL will choose the modeled plan. Validate the proposed design with representative workload and native plan evidence, and review write overhead, storage cost, and other queries before applying it. Do not remove an existing index solely on this comparison."}
ReportIndexImprovementValidation keeps model comparisons distinct from live evidence.
Functions ¶
func BuildPublicReport ¶
func BuildPublicReport(facts *OptimizeResult, engine analysis.AnalysisContext, options analysis.RequestOptions, catalog *sqli18n.Catalog) *analysis.AnalyzeResult
BuildPublicReport projects MySQL optimizer facts into the stable public report. Engine metadata must come from the caller's actual server observation.
func CheckExplainSupport ¶
CheckExplainSupport validates that sql can be handled by the connected EXPLAIN analysis pipeline. Lexical safety violations (such as EXPLAIN modifiers, conditional executable comments, NUL bytes, or multiple statements) and unsupported parsed statement types return sqlgunyu.ErrExplainUnsupported. Parser errors on lexically safe explainable statements are returned separately so callers can distinguish invalid/newer SQL syntax from unsupported statement capabilities.
func RenderMessage ¶
func RenderMessage(catalog *sqli18n.Catalog, lang string, ref *MessageRef) string
RenderMessage renders a persisted reference using the supplied sql-gunyu catalog. Translation templates remain owned by sql-gunyu.
func ToPublicEvaluation ¶
func ToPublicEvaluation(w *WhatIfEvaluation, context analysis.AnalysisContext) analysis.EvaluationReport
ToPublicEvaluation projects one MySQL whole-query evaluation without claiming a native planner cost or a runtime prediction.
func ToPublicIssue ¶
ToPublicIssue projects one MySQL rule finding into the engine-neutral issue shape without inventing physical bindings. Callers that own table snapshots replace Targets and Location with the resolved SQL targets.
func ToPublicSuggestions ¶
func ToPublicSuggestions(old *Issue) []*analysis.Suggestion
ToPublicSuggestions projects MySQL guidance without promoting its SQL text into an executable action.
Types ¶
type AdvisorContext ¶
type AdvisorContext struct {
*AnalyzeContext
Issues []*Issue // 已诊断出的问题
}
AdvisorContext 建议上下文
type AgentConfig ¶
type AgentConfig struct {
DiagnosticPolicy analysis.DiagnosticPolicy
RulePolicy RulePolicy
OptimizationConfig OptimizationConfig
}
AgentConfig is the optimizer policy shape consumed by the MySQL adapter.
func DefaultAgentConfig ¶
func DefaultAgentConfig() *AgentConfig
DefaultAgentConfig returns a fresh optimizer policy snapshot.
type AnalysisSource ¶
type AnalysisSource string
AnalysisSource 问题来源
const ( SourceAST AnalysisSource = "AST" // 静态分析 SourceExplain AnalysisSource = "EXPLAIN" // 动态分析 )
type AnalysisStatus ¶
type AnalysisStatus string
AnalysisStatus describes whether all requested evidence was evaluated.
const ( AnalysisStatusComplete AnalysisStatus = "COMPLETE" AnalysisStatusPartial AnalysisStatus = "PARTIAL" AnalysisStatusUnsupported AnalysisStatus = "UNSUPPORTED" )
type AnalyzeContext ¶
type AnalyzeContext struct {
SQL string // 原始 SQL(始终有值)
Stmt parser.StmtNode // 解析后的 AST(始终有值)
Language string // 语言 (en/zh)
Schema string // 数据库名
Catalog *sqli18n.Catalog // 文案目录
// 以下字段仅动态分析时有值
VTable *explain.VirtualTable // 虚拟表树
AllPhyTables []*explain.VirtualTable // 所有物理表
NativeCost *cost.QueryCost // MySQL EXPLAIN 原生代价摘要
DBCtx *db.DBContext // 数据库上下文
CTE *CTESemantics // CTE 归一化语义缓存
Status AnalysisStatus // 分析完整性
Warnings []Diagnostic // 非致命诊断
Unsupported []Diagnostic // 不可评估能力
// CandidateReasons records terminal candidate-generation decisions so a
// no-candidate result can explain where opportunities were filtered.
CandidateReasons []CandidateReason
// CandidateFunnel records rule-layer candidate counts before the global
// what-if collector sees executable suggestions.
CandidateFunnel CandidateCounts
// 配置
RulePolicy *RulePolicy
OptimizationConfig *OptimizationConfig
DiagnosticPolicy analysis.DiagnosticPolicy
EnabledRules map[string]bool
// 懒加载控制
ExplainJSON *explain.ExplainResult
TableInfos map[relation.Key]*db.TableInfo
// contains filtered or unexported fields
}
AnalyzeContext 分析上下文,包含诊断所需的所有信息 静态分析时 VTable/ExplainJSON/NativeCost/DBCtx 为 nil 动态分析时所有字段都有值
func (*AnalyzeContext) EnsureExplainJSON ¶
func (ctx *AnalyzeContext) EnsureExplainJSON() *explain.ExplainResult
EnsureExplainJSON 按需获取 EXPLAIN
func (*AnalyzeContext) EnsureTableInfos ¶
func (ctx *AnalyzeContext) EnsureTableInfos() map[relation.Key]*db.TableInfo
EnsureTableInfos 按需获取带有 Samples 的 TableInfo
func (*AnalyzeContext) GetCTEExecutionModeForRef ¶
func (ctx *AnalyzeContext) GetCTEExecutionModeForRef(ref *explain.VirtualTable) CTEExecutionMode
GetCTEExecutionModeForRef 返回 CTE 引用节点的执行模式
func (*AnalyzeContext) HasExplain ¶
func (ctx *AnalyzeContext) HasExplain() bool
HasExplain 是否有 EXPLAIN 数据
func (*AnalyzeContext) IsEnabled ¶
func (ctx *AnalyzeContext) IsEnabled(name string) bool
IsEnabled 检查指定检查项是否启用 支持层级检查:如果 "sql_style" 被禁用,则 "sql_style.select_star" 也被禁用
func (*AnalyzeContext) PeekExplainJSON ¶
func (ctx *AnalyzeContext) PeekExplainJSON() *explain.ExplainResult
PeekExplainJSON 返回可能已加载的 EXPLAIN 结果,但不主动触发获取
func (*AnalyzeContext) PeekTableInfos ¶
func (ctx *AnalyzeContext) PeekTableInfos() map[relation.Key]*db.TableInfo
PeekTableInfos 返回可能已加载的物理表统计信息,但不主动触发获取
func (*AnalyzeContext) ResolveCTEColumnToPhysical ¶
func (ctx *AnalyzeContext) ResolveCTEColumnToPhysical(tableNameL, colNameL string) (*db.TableInfo, string)
ResolveCTEColumnToPhysical 解析 CTE 列引用到底层物理表及列名
func (*AnalyzeContext) ResolveTableColumnToPhysical ¶
func (ctx *AnalyzeContext) ResolveTableColumnToPhysical(tableNameL, colNameL string) (*db.TableInfo, string)
ResolveTableColumnToPhysical 解析 table.col 到底层物理表列 table 可以是物理表名、CTE 名或 CTE 别名。
func (*AnalyzeContext) TableInfo ¶
func (ctx *AnalyzeContext) TableInfo(key relation.Key) *db.TableInfo
TableInfo returns metadata for one fully bound physical relation.
func (*AnalyzeContext) TableInfoOf ¶
func (ctx *AnalyzeContext) TableInfoOf(table *explain.VirtualTable) *db.TableInfo
TableInfoOf returns metadata for a bound physical VirtualTable.
type AnalyzeOption ¶
type AnalyzeOption func(*analyzeOptions)
AnalyzeOption configures one low-level static analysis request.
func WithAnalyzeCanonicalizer ¶
func WithAnalyzeCanonicalizer(canonicalizer relation.Canonicalizer) AnalyzeOption
WithAnalyzeCanonicalizer supplies the request-frozen identifier semantics.
func WithAnalyzeCatalog ¶
func WithAnalyzeCatalog(catalog *sqli18n.Catalog) AnalyzeOption
WithAnalyzeCatalog supplies the request's localization catalog.
func WithAnalyzeDefaultDatabase ¶
func WithAnalyzeDefaultDatabase(database string) AnalyzeOption
WithAnalyzeDefaultDatabase supplies the frozen request default used to bind unqualified physical relations during static or connected analysis.
func WithAnalyzeReport ¶
func WithAnalyzeReport(context analysis.AnalysisContext, options analysis.RequestOptions) AnalyzeOption
WithAnalyzeReport supplies request report options without changing rule or model execution.
func WithAnalyzeRuleFilter ¶
func WithAnalyzeRuleFilter(f RuleFilter) AnalyzeOption
func WithAnalyzeRuleSet ¶
func WithAnalyzeRuleSet(rs *RuleSet) AnalyzeOption
func WithAnalyzeServerMajor ¶
func WithAnalyzeServerMajor(major int) AnalyzeOption
WithAnalyzeServerMajor supplies observed version semantics to syntax checks. Zero means no server version was observed.
func WithAnalyzeUnprobedServer ¶
func WithAnalyzeUnprobedServer() AnalyzeOption
WithAnalyzeUnprobedServer defers checks requiring server identifier or version semantics until continuation. Syntax facts still retain original spelling.
type AnalyzerRequires ¶
type AnalyzerRequires int
AnalyzerRequires 分析器依赖声明
const ( RequiresAST AnalyzerRequires = 1 << iota // 仅需 AST RequiresExplain // 仅需 EXPLAIN RequiresBoth = RequiresAST | RequiresExplain // RequiresMetadata identifies checks that need schema or index evidence. RequiresMetadata AnalyzerRequires = 1 << 2 )
type BaselineAlignment ¶
type BaselineAlignment struct {
// Attempted is true when the analysis had enough native and internal plan
// information to try structural validation.
Attempted bool `json:"attempted"`
// Matched is true only when the supported checks for table accesses, indexes,
// join order/algorithms, row estimates, and blocking operators all pass.
Matched bool `json:"matched"`
// Reasons explains why validation was unavailable or which structural check
// failed. An empty slice with Matched=true means all supported checks passed.
Reasons []string `json:"reasons,omitempty"`
}
BaselineAlignment records whether the internal baseline plan is structurally consistent with the native EXPLAIN plan. Alignment affects confidence and diagnostics only; native and internal absolute costs remain incomparable.
type CTEColumnBinding ¶
CTEColumnBinding 描述 CTE 输出列与底层物理列的映射关系 仅当可唯一映射时 Exact 为 true
type CTEEntry ¶
type CTEEntry struct {
NameL string
Def *explain.VirtualTable
IsRecursive bool
RefCount int
ExecMode CTEExecutionMode
OutputBind map[string]CTEColumnBinding // key: 输出列名(lowercase)
}
CTEEntry 表示一个 CTE 定义的归一化语义
type CTEExecutionMode ¶
type CTEExecutionMode uint8
CTEExecutionMode 描述 CTE 在当前上下文中的执行模式
const ( CTEExecUnknown CTEExecutionMode = iota CTEExecMaterialized CTEExecInlined CTEExecRecursiveMaterialized )
type CTERule ¶
type CTERule struct{}
CTERule CTE(公共表表达式)优化规则
func (*CTERule) Analyze ¶
func (r *CTERule) Analyze(ctx *AnalyzeContext) *RuleResult
func (*CTERule) Requires ¶
func (r *CTERule) Requires() AnalyzerRequires
type CTESemantics ¶
type CTESemantics struct {
Entries []*CTEEntry
// contains filtered or unexported fields
}
CTESemantics 统一保存 CTE 的归一化语义
func BuildCTESemantics ¶
func BuildCTESemantics(vt *explain.VirtualTable, exp *explain.ExplainResult) *CTESemantics
BuildCTESemantics 从 VTable 与 EXPLAIN 信息构建 CTE 语义缓存
type CacheTrace ¶
type CacheTrace struct {
// Hits and Misses aggregate all optimization-cache lookups.
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
// Entries is the number of cache entries visible after this analysis.
Entries int `json:"entries"`
// PlanHits and PlanMisses count complete plan-cache lookups.
PlanHits int64 `json:"plan_hits,omitempty"`
PlanMisses int64 `json:"plan_misses,omitempty"`
// AccessPathHits and AccessPathMisses count leaf access-path lookups.
AccessPathHits int64 `json:"access_path_hits,omitempty"`
AccessPathMisses int64 `json:"access_path_misses,omitempty"`
// CardinalityHits and CardinalityMisses count row-estimate lookups.
CardinalityHits int64 `json:"cardinality_hits,omitempty"`
CardinalityMisses int64 `json:"cardinality_misses,omitempty"`
// Version identifies the cache-key schema and model revision.
Version string `json:"version,omitempty"`
}
CacheTrace reports optimization-cache activity for one analysis request.
type CandidateCounts ¶
type CandidateCounts struct {
RelationsExamined int `json:"relations_examined"`
OpportunitiesFound int `json:"opportunities_found"`
CandidatesGenerated int `json:"candidates_generated"`
CandidatesSubmitted int `json:"candidates_submitted"`
CandidatesEvaluated int `json:"candidates_evaluated"`
CandidatesUsed int `json:"candidates_used"`
CandidatesSelected int `json:"candidates_selected"`
CandidatesRecommended int `json:"candidates_recommended"`
}
CandidateCounts summarizes the candidate funnel for operational diagnosis.
type CandidateDecision ¶
type CandidateDecision string
CandidateDecision summarizes the final recommendation decision after the complete candidate pipeline has run. It is distinct from WhatIfStatus: a usable what-if evaluation may still decide not to recommend any candidate.
const ( CandidateDecisionRecommended CandidateDecision = "RECOMMENDED" CandidateDecisionNotRecommended CandidateDecision = "NOT_RECOMMENDED" CandidateDecisionNotEvaluable CandidateDecision = "NOT_EVALUABLE" )
type CandidateDecisionRecord ¶
type CandidateDecisionRecord struct {
Sources []CandidateSource `json:"sources,omitempty"`
IndependentEvaluation *CandidateScenario `json:"independent_evaluation,omitempty"`
BestUsedEvaluation *CandidateScenario `json:"best_used_evaluation,omitempty"`
CandidateID string `json:"candidate_id"`
SuggestionID string `json:"suggestion_id,omitempty"`
IssueID string `json:"issue_id,omitempty"`
Rule string `json:"rule,omitempty"`
Kind CandidateKind `json:"kind"`
Database string `json:"database,omitempty"`
Table string `json:"table,omitempty"`
TableAlias string `json:"table_alias,omitempty"`
QueryBlockID int `json:"query_block_id,omitempty"`
Clause string `json:"clause,omitempty"`
Columns []string `json:"columns,omitempty"`
StageReached CandidateStage `json:"stage_reached"`
Disposition CandidateDisposition `json:"disposition"`
DecisionCode string `json:"decision_code"`
Submitted bool `json:"submitted"`
Evaluated bool `json:"evaluated"`
Valid bool `json:"valid"`
Used bool `json:"used"`
Selected bool `json:"selected"`
Recommended bool `json:"recommended"`
Index *WhatIfCandidateIndex `json:"index,omitempty"`
HintChanges []ConstraintChangeTrace `json:"hint_changes,omitempty"`
Evidence *IndexEvidence `json:"evidence,omitempty"`
Evaluation *CandidateEvaluationSummary `json:"evaluation,omitempty"`
Reason string `json:"reason,omitempty"`
ReasonRef *MessageRef `json:"reason_ref,omitempty"`
NextAction string `json:"next_action_code,omitempty"`
}
CandidateDecisionRecord exposes one candidate's complete progression from rule output through whole-query evaluation and recommendation policy.
type CandidateDisposition ¶
type CandidateDisposition string
CandidateDisposition distinguishes actionable and evaluated candidates from healthy no-opportunity cases, policy filtering, and evidence or capability failures.
const ( CandidateDispositionActionable CandidateDisposition = "ACTIONABLE" CandidateDispositionEvaluatedNotActionable CandidateDisposition = "EVALUATED_NOT_ACTIONABLE" CandidateDispositionNoOpportunity CandidateDisposition = "NO_OPPORTUNITY" CandidateDispositionFilteredByPolicy CandidateDisposition = "FILTERED_BY_POLICY" CandidateDispositionInsufficientEvidence CandidateDisposition = "INSUFFICIENT_EVIDENCE" CandidateDispositionUnsupported CandidateDisposition = "UNSUPPORTED" CandidateDispositionInternalFailure CandidateDisposition = "INTERNAL_FAILURE" )
type CandidateEvaluationSummary ¶
type CandidateEvaluationSummary struct {
Scope WhatIfScope `json:"scope"`
DesignFingerprint string `json:"design_fingerprint,omitempty"`
CoCandidateIDs []string `json:"co_candidate_ids,omitempty"`
PlanDigest string `json:"plan_digest,omitempty"`
TotalCost float64 `json:"total_cost,omitempty"`
CostRatio float64 `json:"cost_ratio,omitempty"`
CostReductionPercent float64 `json:"cost_reduction_percent,omitempty"`
OutputRows int64 `json:"output_rows,omitempty"`
RowsExamined int64 `json:"rows_examined,omitempty"`
}
CandidateEvaluationSummary is the compatibility view of a recorded design. Explicit independent, best-used, and selected scenarios own attribution; CoCandidateIDs prevents interpreting this view as an isolated index effect.
type CandidateKind ¶
type CandidateKind string
CandidateKind identifies the physical-design mutation represented by one candidate. A suggestion may combine an index and a structured hint change.
const ( CandidateKindIndex CandidateKind = "INDEX" CandidateKindHint CandidateKind = "HINT" CandidateKindIndexAndHint CandidateKind = "INDEX_AND_HINT" CandidateKindUnknown CandidateKind = "UNKNOWN" )
type CandidateOutcome ¶
type CandidateOutcome struct {
SelectedDesign *CandidateScenario `json:"selected_design,omitempty"`
Decision CandidateDecision `json:"decision"`
PrimaryDisposition CandidateDisposition `json:"primary_disposition"`
SummaryCode string `json:"summary_code"`
// RecommendationThresholdPercent uses (baseline/candidate-1)*100, the
// efficiency-gain metric used by policy. It differs from cost reduction.
RecommendationThresholdPercent float64 `json:"recommendation_threshold_percent"`
Counts CandidateCounts `json:"counts"`
Search CandidateSearchSummary `json:"search"`
Candidates []CandidateDecisionRecord `json:"candidates"`
Reasons []CandidateReason `json:"reasons"`
Relations []CandidateRelationEvidence `json:"relations"`
}
CandidateOutcome is the canonical evidence and decision record for the complete what-if candidate pipeline, including successful recommendations.
type CandidateReason ¶
type CandidateReason struct {
Code string `json:"code"`
Stage string `json:"stage"`
Disposition CandidateDisposition `json:"disposition"`
Rule string `json:"rule,omitempty"`
Database string `json:"database,omitempty"`
Table string `json:"table,omitempty"`
TableAlias string `json:"table_alias,omitempty"`
QueryBlockID int `json:"query_block_id,omitempty"`
Clause string `json:"clause,omitempty"`
Columns []string `json:"columns,omitempty"`
SuggestionID string `json:"suggestion_id,omitempty"`
ObservedValue string `json:"observed_value,omitempty"`
Threshold string `json:"threshold,omitempty"`
ExistingIndex string `json:"existing_index,omitempty"`
Message string `json:"message,omitempty"`
MessageRef *MessageRef `json:"message_ref,omitempty"`
NextAction string `json:"next_action_code,omitempty"`
}
CandidateReason identifies one terminal decision in the candidate pipeline. Code is stable and language-neutral; Message is display text.
type CandidateRelationEvidence ¶
type CandidateRelationEvidence struct {
Database string `json:"database,omitempty"`
Table string `json:"table"`
TableStructure *TableStructure `json:"table_structure,omitempty"`
Statistics CandidateTableStatistics `json:"statistics"`
Columns []IndexColumnEvidence `json:"columns,omitempty"`
}
CandidateRelationEvidence exposes the schema and statistics that informed candidate eligibility for one physical relation. It never includes table-row contents or sampled values.
type CandidateScenario ¶
type CandidateScenario struct {
Status string `json:"status"`
DesignFingerprint string `json:"design_fingerprint,omitempty"`
ConstraintFingerprint string `json:"constraint_fingerprint,omitempty"`
StatisticsIdentity string `json:"statistics_identity,omitempty"`
BaselineDesignFingerprint string `json:"baseline_design_fingerprint,omitempty"`
Model CostModelIdentity `json:"model"`
Actions []CandidateScenarioAction `json:"actions"`
UsedCandidateIDs []string `json:"used_candidate_ids"`
Plan *ModelPlanEstimate `json:"plan,omitempty"`
Limitations []string `json:"limitations,omitempty"`
}
CandidateScenario preserves one exact design without retaining its full plan tree. NOT_EVALUATED has no numerical plan. All costs share the enclosing baseline/model.
type CandidateScenarioAction ¶
type CandidateScenarioAction struct {
Sources []CandidateSource `json:"sources,omitempty"`
CandidateID string `json:"candidate_id"`
Database string `json:"database"`
Table string `json:"table"`
TableAlias string `json:"table_alias,omitempty"`
QueryBlockID int `json:"query_block_id,omitempty"`
Index *WhatIfCandidateIndex `json:"index,omitempty"`
HintChanges []ConstraintChangeTrace `json:"hint_changes,omitempty"`
}
CandidateScenarioAction is an atomic candidate mutation plus its originating occurrence. An index and hint changes in one candidate must be applied together.
type CandidateSearchStrategy ¶
type CandidateSearchStrategy string
CandidateSearchStrategy identifies how candidate designs were explored.
const ( CandidateSearchNotStarted CandidateSearchStrategy = "NOT_STARTED" CandidateSearchExhaustive CandidateSearchStrategy = "EXHAUSTIVE" CandidateSearchGreedy CandidateSearchStrategy = "GREEDY" )
type CandidateSearchSummary ¶
type CandidateSearchSummary struct {
Strategy CandidateSearchStrategy `json:"strategy"`
CandidateLimit int `json:"candidate_limit,omitempty"`
DesignLimit int `json:"design_limit,omitempty"`
DesignsAttempted int `json:"designs_attempted"`
DesignsEvaluated int `json:"designs_evaluated"`
Truncated bool `json:"truncated"`
PlanSearchTruncated bool `json:"plan_search_truncated,omitempty"`
}
CandidateSearchSummary describes how much of the bounded physical-design search was evaluated. Detailed per-design traces remain opt-in.
type CandidateSource ¶
type CandidateSource struct {
OpportunityID string `json:"opportunity_id,omitempty"`
IssueID string `json:"issue_id"`
SuggestionID string `json:"suggestion_id"`
Rule string `json:"rule,omitempty"`
TableAlias string `json:"table_alias,omitempty"`
QueryBlockID int `json:"query_block_id,omitempty"`
Clause string `json:"clause,omitempty"`
Expression string `json:"expression,omitempty"`
Predicates []CandidateSourcePredicate `json:"predicates,omitempty"`
}
CandidateSource identifies a diagnostic or opportunity and its bound generation context, not predicates proven consumed by an access path. Unknown binding stays empty.
type CandidateSourcePredicate ¶
type CandidateSourcePredicate struct {
Location string `json:"location"`
Expression string `json:"expression,omitempty"`
// contains filtered or unexported fields
}
CandidateSourcePredicate locates the original bound predicate. Expression is display-only and may be empty for unsupported rendering; Location is retained.
type CandidateStage ¶
type CandidateStage string
CandidateStage identifies the furthest stable pipeline stage reached by a candidate before its terminal disposition was assigned.
const ( CandidateStageDiscovery CandidateStage = "DISCOVERY" CandidateStageGeneration CandidateStage = "GENERATION" CandidateStageCollection CandidateStage = "COLLECTION" CandidateStageEvaluation CandidateStage = "EVALUATION" CandidateStageSelection CandidateStage = "SELECTION" CandidateStageRecommendation CandidateStage = "RECOMMENDATION" )
type CandidateTableStatistics ¶
type CandidateTableStatistics struct {
Status string `json:"status"`
Source string `json:"source"`
Confidence float64 `json:"confidence,omitempty"`
Version string `json:"version,omitempty"`
TableRows int64 `json:"table_rows,omitempty"`
TotalPages int64 `json:"total_pages,omitempty"`
RowsPerPage int64 `json:"rows_per_page,omitempty"`
SampledPages int `json:"sampled_pages,omitempty"`
}
CandidateTableStatistics summarizes the bounded metadata snapshot used by candidate generation and cost estimation.
type ConstraintChangeTrace ¶
type ConstraintChangeTrace struct {
// HintID is the stable identity of the parsed SQL index hint.
HintID string `json:"hint_id,omitempty"`
// Operation is the selected structured mutation, currently REMOVE.
Operation string `json:"operation,omitempty"`
// Table identifies the relation whose hint is changed.
Table string `json:"table,omitempty"`
// HintType identifies USE INDEX, FORCE INDEX, or IGNORE INDEX.
HintType string `json:"hint_type,omitempty"`
// HintScope identifies JOIN, ORDER BY, or GROUP BY applicability.
HintScope string `json:"hint_scope,omitempty"`
// IndexNames lists indexes referenced by the original hint.
IndexNames []string `json:"index_names,omitempty"`
}
ConstraintChangeTrace describes a structured query-hint mutation selected by the global search.
type CostModelIdentity ¶
type CostModelIdentity struct {
// Name identifies the planner and cost model implementation that produced
// both estimates.
Name string `json:"name"`
// Version identifies the work-accounting revision used for comparison.
Version string `json:"version,omitempty"`
// Profile names an internal constant set when the server has no native cost
// tables. MySQL 5.6 uses mysql-5.6-internal-5.7-constants, which reuses the
// 5.7 numeric constants and is not a native 5.6 cost. Empty keeps the
// historical unlabeled internal model.
Profile string `json:"profile,omitempty"`
// Unit names the model-specific cost space. The value is neither elapsed
// time nor a unit used by the native database optimizer.
Unit string `json:"unit"`
}
CostModelIdentity identifies the cost space used for both sides of a what-if comparison. Baseline and Candidate are comparable only when this complete identity is equal; none of its costs are durations or native MySQL costs.
type DMLRule ¶
type DMLRule struct{}
DMLRule DML 语句审计规则 检查 INSERT/UPDATE 是否显式设置自增列、SELECT FOR UPDATE 锁等
func (*DMLRule) Analyze ¶
func (r *DMLRule) Analyze(ctx *AnalyzeContext) *RuleResult
func (*DMLRule) Requires ¶
func (r *DMLRule) Requires() AnalyzerRequires
type DesignTrace ¶
type DesignTrace struct {
// DesignFingerprint identifies the hypothetical index and hint mutation set.
DesignFingerprint string `json:"design_fingerprint,omitempty"`
// SuggestionIDs lists suggestions represented by this design.
SuggestionIDs []string `json:"suggestion_ids,omitempty"`
// UsedIndexes lists hypothetical indexes actually used by the resulting plan.
UsedIndexes []string `json:"used_indexes,omitempty"`
// PlanDigest identifies the plan produced for this design.
PlanDigest string `json:"plan_digest,omitempty"`
// TotalCost is that plan's internal whole-query cost.
TotalCost float64 `json:"total_cost,omitempty"`
// Valid reports whether the design produced a usable plan estimate.
Valid bool `json:"valid"`
// Selected reports whether this design won the global search.
Selected bool `json:"selected,omitempty"`
// Reason explains invalidity, rejection, or other search disposition.
Reason string `json:"reason,omitempty"`
}
DesignTrace records one physical-design scenario considered by global search.
type Diagnostic ¶
type Diagnostic struct {
Code string `json:"code"`
Message string `json:"message"`
Database string `json:"database,omitempty"`
Table string `json:"table,omitempty"`
}
Diagnostic is a structured non-fatal analysis limitation.
type ExplainFloat64 ¶
type ExplainFloat64 struct {
RawValue float64 `json:"rawValue"`
ToolTip string `json:"toolTip"`
Results []*ExplainRuleResult `json:"results"`
}
ExplainFloat64 explain float wrapper
type ExplainInt64 ¶
type ExplainInt64 struct {
RawValue int64 `json:"rawValue"`
ToolTip string `json:"toolTip"`
Results []*ExplainRuleResult `json:"results"`
}
ExplainInt64 explain int wrapper
type ExplainRow ¶
type ExplainRow struct {
ID int `json:"id"`
SelectType ExplainString `json:"selectType"`
TableName string `json:"tableName"`
Partitions string `json:"partitions"`
AccessType ExplainString `json:"accessType"`
PossibleKeys []string `json:"possibleKeys"`
Key string `json:"key"`
KeyLen string `json:"keyLen"`
Ref []string `json:"ref"`
Rows ExplainInt64 `json:"rows"`
Filtered float64 `json:"filtered"`
Scalability string `json:"scalability"`
Extra ExplainString `json:"extra"`
Issues []*ExplainRowIssue `json:"issues,omitempty"`
// contains filtered or unexported fields
}
ExplainRow single explain row
type ExplainRowIssue ¶
type ExplainRowIssue struct {
Severity analysis.Severity `json:"severity"`
Message string `json:"message"`
MessageRef *MessageRef `json:"message_ref,omitempty"`
}
ExplainRowIssue represents an issue found on a single explain row.
type ExplainRule ¶
type ExplainRule struct {
Key string
ExplainHeader string
Msg *i18n.Message
Level ExplainRuleLevel
Params map[string]any
}
ExplainRule explain rule
type ExplainRuleLevel ¶
type ExplainRuleLevel int
ExplainRuleLevel explain rule level
const ( ExplainRuleLevelNormal ExplainRuleLevel = 0 ExplainRuleLevelNotice ExplainRuleLevel = 1 ExplainRuleLevelWarn ExplainRuleLevel = 2 ExplainRuleLevelError ExplainRuleLevel = 3 ExplainRuleLevelPanic ExplainRuleLevel = 4 )
type ExplainRuleResult ¶
type ExplainRuleResult struct {
Msg string `json:"msg"`
MessageRef *MessageRef `json:"message_ref,omitempty"`
Level ExplainRuleLevel `json:"level"`
}
ExplainRuleResult explain rule result
type ExplainString ¶
type ExplainString struct {
ToolTipRefs []MessageRef `json:"tool_tip_refs,omitempty"`
ToolTipSeparator *MessageRef `json:"tool_tip_separator,omitempty"`
RawValue string `json:"rawValue"`
ToolTip string `json:"toolTip"`
Results []*ExplainRuleResult `json:"results"`
}
ExplainString explain string wrapper
type ExplainThresholdConfig ¶
type ExplainThresholdConfig struct {
RowsMax int64 // rows 告警阈值,默认 100000
FilterMaxRows int64 // filtered 告警中的 rows 阈值,默认 100000
FilterMinRatio float64 // filtered 告警阈值,默认 20
}
ExplainThresholdConfig EXPLAIN 规则阈值配置
func DefaultExplainThresholdConfig ¶
func DefaultExplainThresholdConfig() *ExplainThresholdConfig
DefaultExplainThresholdConfig 返回 EXPLAIN 阈值默认配置
type GroupByOrderByRule ¶
type GroupByOrderByRule struct{}
GroupByOrderByRule GROUP BY / ORDER BY 写法规则 通过 AST 分析 GROUP BY 和 ORDER BY 子句的写法问题
func (*GroupByOrderByRule) Analyze ¶
func (r *GroupByOrderByRule) Analyze(ctx *AnalyzeContext) *RuleResult
func (*GroupByOrderByRule) Checks ¶
func (r *GroupByOrderByRule) Checks() []RuleCheck
Checks declares execution dependencies for each selectable check.
func (*GroupByOrderByRule) Name ¶
func (r *GroupByOrderByRule) Name() string
func (*GroupByOrderByRule) Requires ¶
func (r *GroupByOrderByRule) Requires() AnalyzerRequires
func (*GroupByOrderByRule) SubRules ¶
func (r *GroupByOrderByRule) SubRules() []string
type HintChangeOperation ¶
type HintChangeOperation string
HintChangeOperation identifies a supported structured query-hint mutation.
const (
HintChangeRemove HintChangeOperation = "REMOVE"
)
type IndexColumnEvidence ¶
type IndexColumnEvidence struct {
Column string `json:"column"`
Cardinality int64 `json:"cardinality"`
Selectivity float64 `json:"selectivity"`
}
IndexColumnEvidence contains language-neutral statistics used to explain an index recommendation.
type IndexEvidence ¶
type IndexEvidence struct {
TableRows int64 `json:"table_rows,omitempty"`
Columns []IndexColumnEvidence `json:"columns,omitempty"`
}
IndexEvidence contains the facts used to render a recommendation basis.
type IndexKeyPart ¶
type IndexKeyPart struct {
Column string `json:"column,omitempty"`
Expression string `json:"expression,omitempty"`
PrefixLength int `json:"prefix_length,omitempty"`
Descending bool `json:"descending,omitempty"`
}
IndexKeyPart describes one ordered physical index key part.
type IndexSpec ¶
type IndexSpec struct {
Schema string `json:"schema,omitempty"`
Table string `json:"table"`
Name string `json:"name,omitempty"`
Unique bool `json:"unique"`
Method string `json:"method,omitempty"`
KeyParts []IndexKeyPart `json:"key_parts"`
CoveringColumns []string `json:"covering_columns,omitempty"`
}
IndexSpec is the language-neutral physical identity of a recommended index.
type Issue ¶
type Issue struct {
ID string `json:"id"` // 唯一标识,如 "IDX001"
Rule string `json:"rule,omitempty"` // 触发规则名
Source AnalysisSource `json:"source"` // 来源: AST 或 EXPLAIN
Category IssueCategory `json:"category"` // 问题分类
Type IssueType `json:"type"` // 问题类型
Severity analysis.Severity `json:"severity"` // 严重程度
Clause string `json:"clause,omitempty"` // SQL 子句,如 WHERE/JOIN_ON/GROUP_BY/PLAN
Database string `json:"database,omitempty"` // 涉及的 database
Table string `json:"table"` // 涉及的表名
TableAlias string `json:"table_alias,omitempty"` // 涉及的表别名
Columns []string `json:"columns"` // 涉及的列名
QueryBlockID int `json:"query_block_id,omitempty"` // 子查询块 ID(select_id)
PlanPath string `json:"plan_path,omitempty"` // 执行计划路径
ExplainLine int `json:"explain_line"` // 对应 EXPLAIN 行号(-1 表示来自 AST)
ExprSQL string `json:"expr_sql,omitempty"` // 命中的 SQL 片段
StartOffset int `json:"start_offset,omitempty"`
EndOffset int `json:"end_offset,omitempty"`
StartLine int `json:"start_line,omitempty"`
StartColumn int `json:"start_column,omitempty"`
EndLine int `json:"end_line,omitempty"`
EndColumn int `json:"end_column,omitempty"`
LocationKey string `json:"location_key,omitempty"` // 稳定定位键
Message string `json:"message"` // 问题描述
Detail string `json:"detail"` // 详细说明
MessageRef *MessageRef `json:"message_ref,omitempty"` // 语言无关的问题描述引用
DetailRef *MessageRef `json:"detail_ref,omitempty"` // 语言无关的详细说明引用
// EXPLAIN 上下文(仅 SourceExplain 时有值)
AccessType string `json:"access_type,omitempty"` // EXPLAIN type 字段
CurrentKey string `json:"current_key,omitempty"` // 当前使用的索引
PossibleKeys string `json:"possible_keys,omitempty"` // 可用索引
Rows int64 `json:"rows,omitempty"` // 预估扫描行数
Filtered float64 `json:"filtered,omitempty"` // 过滤比例
Extra string `json:"extra,omitempty"` // EXPLAIN Extra 字段
// Suggestions are candidate remedies; physical compatibility is evaluated separately.
Suggestions []*Suggestion `json:"suggestions,omitempty"`
// contains filtered or unexported fields
}
Issue retains MySQL rule evidence before report assembly.
func (*Issue) LocationSignature ¶
LocationSignature 返回定位签名(不含 Type),用于区分同类问题的不同位置。
type IssueCategory ¶
type IssueCategory string
IssueCategory 问题分类
const ( IssueCategoryIndex IssueCategory = "INDEX" // 索引问题 IssueCategoryJoin IssueCategory = "JOIN" // JOIN 问题 IssueCategorySortGrp IssueCategory = "SORT_GRP" // 排序/分组问题 IssueCategorySubquery IssueCategory = "SUBQUERY" // 子查询问题 IssueCategorySQLStyle IssueCategory = "SQL" // SQL 写法问题 IssueCategoryDML IssueCategory = "DML" // DML 审计问题 )
type IssueType ¶
type IssueType string
IssueType 问题具体类型
const ( // 索引相关 IssueFullTableScan IssueType = "FULL_TABLE_SCAN" IssueOptIndexScan IssueType = "OPT_INDEX_SCAN" IssueIndexNotUsed IssueType = "INDEX_NOT_USED" // 存在未覆盖条件,但当前无法给出可执行索引创建建议 IssueMissingIndexBlocked IssueType = "MISSING_INDEX_BLOCKED" // 不适合建立索引列类型 IssueNotSuitableForIndex IssueType = "NOT_SUITABLE_FOR_INDEX" IssuePoorSelectivity IssueType = "POOR_SELECTIVITY" IssueExplainRowsTooMany IssueType = "EXPLAIN_ROWS_TOO_MANY" IssueCoveringIndexMissed IssueType = "COVERING_INDEX_MISSED" IssueBadForceIndex IssueType = "BAD_FORCE_INDEX" IssueBadIgnoreIndex IssueType = "BAD_IGNORE_INDEX" IssueFuncOnIndexCol IssueType = "FUNC_ON_INDEX_COL" IssueImplicitConversion IssueType = "IMPLICIT_CONVERSION" IssueLeftPrefixViolation IssueType = "LEFT_PREFIX_VIOLATION" IssueLikeLeadingWildcard IssueType = "LIKE_LEADING_WILDCARD" // JOIN 相关(EXPLAIN 动态分析) IssueJoinFullScan IssueType = "JOIN_FULL_SCAN" IssueBadDriverTable IssueType = "BAD_DRIVER_TABLE" IssueJoinBufferUsed IssueType = "JOIN_BUFFER_USED" IssueJoinNoIndex IssueType = "JOIN_NO_INDEX" IssueJoinCTEFullScan IssueType = "JOIN_CTE_FULL_SCAN" // JOIN 相关(AST 静态分析) IssueJoinMaxTable IssueType = "JOIN_MAX_TABLE" IssueJoinNoCondition IssueType = "JOIN_NO_CONDITION" IssueJoinWhereColNoAlias IssueType = "JOIN_WHERE_COL_NO_ALIAS" IssueJoinFieldNoAlias IssueType = "JOIN_FIELD_NO_ALIAS" IssueJoinFieldWildcard IssueType = "JOIN_FIELD_WILDCARD" IssueJoinOnOpCol IssueType = "JOIN_ON_OP_COL" IssueJoinOnNotIndexAST IssueType = "JOIN_ON_NOT_INDEX_AST" IssueJoinOnColTypeMismatch IssueType = "JOIN_ON_COL_TYPE_MISMATCH" IssueJoinOnColCharsetMismatch IssueType = "JOIN_ON_COL_CHARSET_MISMATCH" IssueJoinCrossSchema IssueType = "JOIN_CROSS_SCHEMA" // 排序/分组相关 IssueFilesort IssueType = "FILESORT" IssueTempTable IssueType = "TEMP_TABLE" IssueSortGroupNoIndex IssueType = "SORT_GROUP_NO_INDEX" // GROUP BY / ORDER BY 写法相关 IssueGroupByTooManyItems IssueType = "GROUPBY_TOO_MANY_ITEMS" IssueGroupByOpOnItem IssueType = "GROUPBY_OP_ON_ITEM" IssueGroupByDiffTable IssueType = "GROUPBY_DIFF_TABLE" IssueGroupByConstOrOrdinal IssueType = "GROUPBY_CONST_OR_ORDINAL" IssueGroupByNoOrderBy IssueType = "GROUPBY_NO_ORDER_BY" IssueGroupByNondeterministic IssueType = "GROUPBY_NONDETERMINISTIC" IssueOrderByTooManyItems IssueType = "ORDERBY_TOO_MANY_ITEMS" IssueOrderByOpOnItem IssueType = "ORDERBY_OP_ON_ITEM" IssueOrderByConstItem IssueType = "ORDERBY_CONST_ITEM" IssueOrderByNotColumn IssueType = "ORDERBY_NOT_COLUMN" IssueOrderByMixedAscDesc IssueType = "ORDERBY_MIXED_ASC_DESC" IssueOrderByColumnLength IssueType = "ORDERBY_COLUMN_LENGTH" // 子查询相关 IssueDependentSubquery IssueType = "DEPENDENT_SUBQUERY" IssueExpensiveMaterialize IssueType = "EXPENSIVE_MATERIALIZE" IssueSubqueryToJoin IssueType = "SUBQUERY_TO_JOIN" // 子查询审计相关 IssueWhereHasSubquery IssueType = "WHERE_HAS_SUBQUERY" IssueWhereScalarSubquery IssueType = "WHERE_SCALAR_SUBQUERY" IssueSelectScalarSubquery IssueType = "SELECT_SCALAR_SUBQUERY" IssueMaxNestedSubquery IssueType = "MAX_NESTED_SUBQUERY" IssueMaxSubqueryCount IssueType = "MAX_SUBQUERY_COUNT" IssueNotInNullableColumn IssueType = "NOT_IN_NULLABLE_COLUMN" // SQL 写法 IssueSelectStar IssueType = "SELECT_STAR" IssueLimitNoOrderBy IssueType = "LIMIT_NO_ORDER_BY" // SQL 审计 IssueSQLTooLong IssueType = "SQL_TOO_LONG" IssueWhereInTooMany IssueType = "WHERE_IN_TOO_MANY" IssueWhereInNoWhere IssueType = "WHERE_IN_NO_WHERE" IssueLimitExceed IssueType = "LIMIT_EXCEED" IssueLimitNoUseOffset IssueType = "LIMIT_NO_USE_OFFSET" IssueLimitOffsetExceed IssueType = "LIMIT_OFFSET_EXCEED" IssueForbiddenFunc IssueType = "FORBIDDEN_FUNC" IssueValueStringSpace IssueType = "VALUE_STRING_SPACE" // WHERE 审计 IssueWhereNoWhere IssueType = "WHERE_NO_WHERE" IssueWhereLikeFuzzyMatch IssueType = "WHERE_LIKE_FUZZY_MATCH" IssueWhereLikeNoWildcard IssueType = "WHERE_LIKE_NO_WILDCARD" IssueWhereCompareNull IssueType = "WHERE_COMPARE_NULL" IssueWhereOrDiffTable IssueType = "WHERE_OR_DIFF_TABLE" IssueWhereOpOnColumn IssueType = "WHERE_OP_ON_COLUMN" IssueWhereIndexInvalidNot IssueType = "WHERE_INDEX_INVALID_NOT" IssueWhereIndexInvalidOp IssueType = "WHERE_INDEX_INVALID_OP" IssueWhereCheckHasIndex IssueType = "WHERE_CHECK_HAS_INDEX" IssueWhereCheckIndexValType IssueType = "WHERE_CHECK_INDEX_VAL_TYPE" IssueWhereCombineIndexLeft IssueType = "WHERE_COMBINE_INDEX_LEFTMOST" // CTE 相关 IssueCTESingleRefMaterialize IssueType = "CTE_SINGLE_REF_MATERIALIZE" // CTE 仅引用一次却被物化 IssueCTERecursiveNoLimit IssueType = "CTE_RECURSIVE_NO_LIMIT" // 递归 CTE 无终止限制 // DML 审计 IssueInsertAutoIncrement IssueType = "INSERT_AUTOINCREMENT" IssueInsertRequireCols IssueType = "INSERT_REQUIRE_COLUMNS" IssueLockUpdate IssueType = "LOCK_UPDATE" IssueUpdateDeleteNoWhere IssueType = "UPDATE_DELETE_NO_WHERE" )
const IssueIndexDesignImprovement IssueType = "INDEX_DESIGN_IMPROVEMENT"
IssueIndexDesignImprovement is a post-evaluation, model-qualified finding.
type JoinRule ¶
type JoinRule struct{}
JoinRule JOIN 规则 通过 EXPLAIN 结果分析 JOIN 相关问题,并生成索引建议
func (*JoinRule) Analyze ¶
func (r *JoinRule) Analyze(ctx *AnalyzeContext) *RuleResult
func (*JoinRule) Requires ¶
func (r *JoinRule) Requires() AnalyzerRequires
type JoinStaticRule ¶
type JoinStaticRule struct{}
JoinStaticRule JOIN 静态分析规则 通过 AST 分析 JOIN 相关写法问题(不依赖 EXPLAIN)
func (*JoinStaticRule) Analyze ¶
func (r *JoinStaticRule) Analyze(ctx *AnalyzeContext) *RuleResult
func (*JoinStaticRule) Checks ¶
func (r *JoinStaticRule) Checks() []RuleCheck
Checks declares execution dependencies for each selectable check.
func (*JoinStaticRule) Name ¶
func (r *JoinStaticRule) Name() string
func (*JoinStaticRule) Requires ¶
func (r *JoinStaticRule) Requires() AnalyzerRequires
func (*JoinStaticRule) SubRules ¶
func (r *JoinStaticRule) SubRules() []string
type MessageRef ¶
type MessageRef struct {
ID string `json:"id"`
Args map[string]interface{} `json:"args,omitempty"`
Default string `json:"default,omitempty"`
}
MessageRef identifies one sql-gunyu-owned message template and its language-neutral template arguments. Default is persisted so artifacts can still render a useful fallback after catalog or version changes.
func NewMessageRef ¶
func NewMessageRef(message *goi18n.Message, args map[string]interface{}) *MessageRef
NewMessageRef creates a persistable reference to a sql-gunyu message.
type ModelAccessSnapshot ¶
type ModelAccessSnapshot struct {
Database string `json:"database,omitempty"`
PhysicalTable string `json:"physical_table"`
Alias string `json:"alias,omitempty"`
QueryBlockID int `json:"query_block_id,omitempty"`
PlanPath string `json:"plan_path,omitempty"`
AccessMethod string `json:"access_method"`
IndexUsed string `json:"index_used,omitempty"`
RowsExamined int64 `json:"rows_examined"`
// contains filtered or unexported fields
}
ModelAccessSnapshot describes one relation access in an internal modeled plan.
type ModelPlanEstimate ¶
type ModelPlanEstimate struct {
// TotalCost is the cumulative internal work estimate for producing all rows
// from the complete plan. It includes the modeled work of all child operators.
TotalCost float64 `json:"total_cost"`
// StartupCost is the cumulative internal work required before the plan root
// can emit its first output row, or its first batch for a batched operator, to
// the executor's result consumer. It does not include protocol serialization,
// network transfer, driver buffering, or time until an application receives
// data. A fully blocking operator commonly has StartupCost == TotalCost.
StartupCost float64 `json:"startup_cost,omitempty"`
// OutputRows is the estimated number of rows emitted by the plan root. A
// semantics-preserving index change should not materially change this value.
OutputRows int64 `json:"output_rows,omitempty"`
// RowsExamined is accumulated modeled row-processing work across the plan.
// It is not equivalent to one table's MySQL rows_examined_per_scan value.
RowsExamined int64 `json:"rows_examined,omitempty"`
// PlanDigest is a deterministic fingerprint of the modeled physical plan
// shape and relevant physical properties; it is not a SQL fingerprint.
PlanDigest string `json:"plan_digest,omitempty"`
// RootOperator names the root physical operator selected by the internal
// planner, such as LIMIT, SORT, or NESTED_LOOP_JOIN.
RootOperator string `json:"root_operator,omitempty"`
// AccessMethod summarizes the modeled access only for a single-access plan.
// Multi-access plans expose ownership through Accesses instead.
AccessMethod string `json:"access_method,omitempty"`
// IndexUsed is the index used by the single summarized access.
IndexUsed string `json:"index_used,omitempty"`
// Accesses preserves relation ownership for every modeled table access.
Accesses []ModelAccessSnapshot `json:"accesses,omitempty"`
// NeedsSorting reports whether the modeled query contains a sort operator.
NeedsSorting bool `json:"needs_sorting,omitempty"`
// LooseScanUsesRowMarginal records a conservative lookup-work estimate
// without a conditional count of the distinct keys surviving the filter.
LooseScanUsesRowMarginal bool `json:"loose_scan_uses_row_marginal,omitempty"`
// FirstMatchUsesUnconditionedFanout records a ref estimate that omits
// fixed suffix keys used by the probe when costing lookup fanout.
FirstMatchUsesUnconditionedFanout bool `json:"first_match_uses_unconditioned_fanout,omitempty"`
// CostLower and CostUpper bound TotalCost within recorded operator cost
// intervals (such as DuplicateWeedout memory/disk storage uncertainty).
// Both are populated only when HasCostInterval is true.
CostLower float64 `json:"cost_lower,omitempty"`
// CostUpper is the upper bound of TotalCost when HasCostInterval is true.
CostUpper float64 `json:"cost_upper,omitempty"`
// HasCostInterval reports whether CostLower and CostUpper represent a
// recorded operator cost interval for this plan.
HasCostInterval bool `json:"has_cost_interval,omitempty"`
}
ModelPlanEstimate is a whole-query estimate produced by the internal planner. Baseline and candidate estimates in one WhatIfEvaluation always share the same logical query, statistics snapshot, model identity, and cost unit.
type NativeAccessSnapshot ¶
type NativeAccessSnapshot struct {
// Table is the relation name or alias reported by MySQL.
Table string `json:"table"`
// Database and PhysicalTable identify a uniquely bound physical relation.
Database string `json:"database,omitempty"`
PhysicalTable string `json:"physical_table,omitempty"`
Alias string `json:"alias,omitempty"`
QueryBlockID int `json:"query_block_id,omitempty"`
PlanPath string `json:"plan_path,omitempty"`
BindingStatus string `json:"binding_status,omitempty"`
// AccessMethod is the native access_type, such as ALL, range, ref, or eq_ref.
AccessMethod string `json:"access_method"`
// PossibleKeys lists indexes MySQL considered legal for this access.
PossibleKeys []string `json:"possible_keys,omitempty"`
// IndexUsed is the index selected by the native plan, when present.
IndexUsed string `json:"index_used,omitempty"`
// RowsExamined is MySQL's rows_examined_per_scan estimate.
RowsExamined int64 `json:"rows_examined"`
// OutputRows is MySQL's rows_produced_per_join estimate.
OutputRows int64 `json:"output_rows"`
// Filtered is MySQL's estimated percentage of rows surviving attached filters.
Filtered float64 `json:"filtered"`
// ReadCost, EvalCost, and PrefixCost retain native per-access cost components.
ReadCost float64 `json:"read_cost,omitempty"`
EvalCost float64 `json:"eval_cost,omitempty"`
PrefixCost float64 `json:"prefix_cost,omitempty"`
// UsingFilesort and UsingTemporaryTable expose native blocking-work flags.
UsingFilesort bool `json:"using_filesort,omitempty"`
UsingTemporaryTable bool `json:"using_temporary_table,omitempty"`
}
NativeAccessSnapshot describes one table-access node from the native MySQL EXPLAIN plan. Multiple entries may refer to the same table in self joins or separate query blocks.
type NativeExplainBaseline ¶
type NativeExplainBaseline struct {
// Engine identifies the database engine that produced the EXPLAIN result.
Engine string `json:"engine"`
// EngineVersion is omitted when the server version is unavailable.
EngineVersion string `json:"engine_version,omitempty"`
// QueryCost is the root query_cost reported by EXPLAIN FORMAT=JSON.
// It is nil when the server does not report cost_info, including MySQL 5.6.
// Nil is not zero; a pointer to 0 is a reported zero cost. Do not compare
// this value with the internal what-if model.
QueryCost *float64 `json:"query_cost,omitempty"`
// Accesses preserves table-access estimates separately from the root cost so
// callers do not mistake per-table rows or CPU cost for whole-query metrics.
Accesses []NativeAccessSnapshot `json:"accesses,omitempty"`
}
NativeExplainBaseline describes MySQL's estimate for the physical plan that is legal under the schema and query hints currently present in the database. Its cost values are native EXPLAIN estimates and must not be compared as absolute values with the internal what-if model.
type OpportunityKind ¶
type OpportunityKind string
OpportunityKind selects an implemented candidate evaluation path.
const OpportunityIndexDesign OpportunityKind = "INDEX_DESIGN"
OpportunityIndexDesign explores a physical index design without a diagnosis.
type OpportunityTarget ¶
type OpportunityTarget struct {
Relation RelationRef
TableAlias string
QueryBlockID int
PlanPath string
Clause string
ExprSQL string
}
OpportunityTarget identifies the bound occurrence that motivated exploration.
type OptimizationConfig ¶
type OptimizationConfig struct {
MaxIndexColumns int // 建议索引最大列数,默认 5
MinImprovementPercent float64 // 最小提升百分比,默认 5.26
MinColumnSelectivity float64 // Deprecated: parsed for compatibility; no longer gates candidate admission.
MaxNewIndexesPerTable int // 每表最多推荐新索引数,默认 3
MaxGlobalCandidates int // 全局成本穷举的候选索引上限,默认 8
MaxGlobalDesigns int // 全局成本穷举的 Physical Design 上限,默认 4096
EnableOptimizationTrace bool // 输出候选设计、拒绝方案、统计来源、基线校验和缓存 trace
MaxOptimizationTraceEntries int // trace 中最多保留的候选设计数,默认 128
}
OptimizationConfig configures candidate generation, cost comparison, search-space limits, and optimization tracing.
func DefaultOptimizationConfig ¶
func DefaultOptimizationConfig() *OptimizationConfig
DefaultOptimizationConfig 返回默认配置
func (OptimizationConfig) Clone ¶
func (config OptimizationConfig) Clone() OptimizationConfig
Clone returns an independent optimization configuration.
func (OptimizationConfig) Resolve ¶
func (config OptimizationConfig) Resolve() (OptimizationConfig, error)
Resolve validates and fills zero values from the optimization defaults.
func (OptimizationConfig) Validate ¶
func (config OptimizationConfig) Validate() error
Validate checks explicitly configured optimization values. Zero means unspecified.
type OptimizationOpportunity ¶
type OptimizationOpportunity struct {
ID string
Kind OpportunityKind
Rule string
Source AnalysisSource
Target OpportunityTarget
ReasonCode string
ReasonRef *MessageRef
Suggestions []*Suggestion
// contains filtered or unexported fields
}
OptimizationOpportunity contains screened suggestions, not a discovery Issue. Bound parser objects are borrowed read-only. Custom rules must supply a resolvable target; unknown bindings are rejected during candidate collection.
type OptimizationTrace ¶
type OptimizationTrace struct {
// CandidateDesigns records every physical-design scenario retained for trace
// reporting, including validity and selection state.
CandidateDesigns []DesignTrace `json:"candidate_designs,omitempty"`
// BaselinePlan summarizes the current-design internal plan.
BaselinePlan PlanTrace `json:"baseline_plan"`
// SelectedPlan summarizes the winning candidate or retained baseline plan.
SelectedPlan PlanTrace `json:"selected_plan"`
// RejectedPlans explains why other valid or invalid scenarios did not win.
RejectedPlans []RejectedPlan `json:"rejected_plans,omitempty"`
// StatsSources records the statistics evidence used per physical table.
StatsSources []StatsTrace `json:"stats_sources,omitempty"`
// Validation mirrors BaselineAlignment with trace-local diagnostics.
Validation ValidationTrace `json:"validation"`
// Cache reports optimization-cache activity for this request.
Cache CacheTrace `json:"cache"`
}
OptimizationTrace exposes optional diagnostic detail about candidate search, plan validation, statistics, and cache behavior.
type OptimizeResult ¶
type OptimizeResult struct {
RuleSetName string `json:"rule_set_name,omitempty"`
RulesUsed []string `json:"rules_used,omitempty"`
// Database is the request default database, not a claim that every relation uses it.
Database string `json:"database,omitempty"`
// Status reports whether every requested analysis capability completed.
Status AnalysisStatus `json:"status"`
// Warnings and Unsupported retain non-fatal structured degradation reasons.
Warnings []Diagnostic `json:"warnings,omitempty"`
Unsupported []Diagnostic `json:"unsupported,omitempty"`
// SQL is the original statement supplied by the caller.
SQL string `json:"sql"`
// Language identifies the language used by the materialized display strings.
Language string `json:"language,omitempty"`
// Issues contains stable semantic diagnostics and their candidate actions.
Issues []*Issue `json:"issues"`
// NativeExplain separates native MySQL plan facts from internal model costs.
NativeExplain *NativeExplainBaseline `json:"native_explain,omitempty"`
// WhatIf is the canonical whole-query comparison in one internal cost space.
WhatIf *WhatIfEvaluation `json:"what_if,omitempty"`
// TablesAnalyzed lists distinct physical relations visited during analysis.
TablesAnalyzed []RelationRef `json:"tables_analyzed"`
// TableStructures contains server-returned definitions for the physical
// relations analyzed by this request.
TableStructures []TableStructure `json:"table_structures,omitempty"`
// contains filtered or unexported fields
}
OptimizeResult contains discovery facts; BuildPublicReport materializes final evaluation-derived findings without mutating these facts. NativeExplain describes the database's current plan, while WhatIf compares hypothetical designs in a separate internal cost space; their absolute costs are intentionally not interchangeable.
func Merge ¶
func Merge(a, b *OptimizeResult) *OptimizeResult
Merge 合并两个 OptimizeResult 去重规则:相同 MergeKey(位置签名 + Type)保留 Severity 更高的,并合并其 Suggestions
func RenderResult ¶
func RenderResult(result *OptimizeResult, catalog *sqli18n.Catalog, lang string) *OptimizeResult
RenderResult refreshes all display strings for which structured references are available. It mutates and returns result so persisted results can be localized without re-running SQL analysis.
func (*OptimizeResult) Sort ¶
func (r *OptimizeResult) Sort()
Sort orders issues and suggestions by stable semantic keys. Severity and priority remain the primary keys; ties must not inherit map iteration order.
type Optimizer ¶
type Optimizer struct {
// contains filtered or unexported fields
}
Optimizer SQL 优化分析器
func NewOptimizerWithPolicies ¶
func NewOptimizerWithPolicies(rulePolicy RulePolicy, optimizationConfig OptimizationConfig, policy analysis.DiagnosticPolicy) *Optimizer
NewOptimizerWithPolicies creates an optimizer from frozen policy snapshots. Agent constructors resolve and validate all values before calling it.
func (*Optimizer) Analyze ¶
Analyze performs connected analysis by combining AST rules, native EXPLAIN facts, metadata-aware diagnostics, and whole-query what-if evaluation. The result keeps NativeExplain in the database's cost space and WhatIf in the internal model space; callers must not compare their absolute costs.
func (*Optimizer) AnalyzePreparedWithOptions ¶
func (o *Optimizer) AnalyzePreparedWithOptions(dbCtx *db.DBContext, sql string, stmt parser.StmtNode, opts ...AnalyzeOption) (*OptimizeResult, error)
AnalyzePreparedWithOptions analyzes an already parsed statement. It is used by Agent so request options, database snapshots, and SQL parsing are resolved once before entering the pinned-connection callback.
func (*Optimizer) AnalyzeStatic ¶
func (o *Optimizer) AnalyzeStatic(sql string, lang string, opts ...AnalyzeOption) (*OptimizeResult, error)
AnalyzeStatic performs SQL-text analysis without a database connection. Only rules whose declared dependency is AST-only are executed. Its OptimizeResult remains the compatibility surface for existing optimizer consumers.
func (*Optimizer) AnalyzeStaticFacts ¶
func (o *Optimizer) AnalyzeStaticFacts(sql string, lang string, analyzeOpts *analyzeOptions, catalog *sqli18n.Catalog) (*OptimizeResult, error)
AnalyzeStaticFacts runs AST-only analysis with already-resolved options for report assembly inside this package.
func (*Optimizer) AnalyzeStaticPublic ¶
func (o *Optimizer) AnalyzeStaticPublic(sql string, lang string, opts ...AnalyzeOption) (*analysis.AnalyzeResult, error)
AnalyzeStaticPublic returns the stable public report from AST-only facts.
func (*Optimizer) AnalyzeWithOptions ¶
func (o *Optimizer) AnalyzeWithOptions(dbCtx *db.DBContext, sql string, opts ...AnalyzeOption) (*OptimizeResult, error)
func (*Optimizer) ExplainRows ¶
ExplainRows executes traditional EXPLAIN and returns its normalized rows. It does not run optimizer rules or produce issues and suggestions.
func (*Optimizer) PrepareAnalysis ¶
func (o *Optimizer) PrepareAnalysis(ctx context.Context, sql, lang string, options ...AnalyzeOption) (*PreparedAnalysis, error)
PrepareAnalysis parses and executes shared AST checks without opening a connection.
type PlanTrace ¶
type PlanTrace struct {
// PlanDigest identifies the traced internal physical plan.
PlanDigest string `json:"plan_digest,omitempty"`
// RootOperator names the root of the traced plan.
RootOperator string `json:"root_operator,omitempty"`
// TotalCost is the complete internal cost of the traced plan.
TotalCost float64 `json:"total_cost,omitempty"`
// OutputRows is the root cardinality estimate.
OutputRows int64 `json:"output_rows,omitempty"`
// RowsExamined is accumulated modeled row-processing work.
RowsExamined int64 `json:"rows_examined,omitempty"`
}
PlanTrace is a compact model-plan summary included in optimization traces.
type PostProcessor ¶
type PostProcessor interface {
// Name 返回后处理器名称
Name() string
// Process 基于所有 Rule 的结果进行全局优化。
// 返回替换后的完整 Issue 集合。没有协调动作时必须返回原集合。
Process(ctx *AnalyzeContext, results []*RuleResult) []*Issue
}
PostProcessor 全局后处理器 在所有 Rule 执行完成后运行,处理跨 Rule 的优化逻辑
type PredictedChange ¶
type PredictedChange struct {
// CostRatio is Candidate.TotalCost / Baseline.TotalCost. Values below one
// mean the candidate is cheaper in the internal model.
CostRatio float64 `json:"cost_ratio,omitempty"`
// CostReductionPercent is (baseline-candidate)/baseline*100, clamped to the
// range 0..100. It is a model prediction, not measured runtime improvement.
CostReductionPercent float64 `json:"cost_reduction_percent,omitempty"`
// PredictedSpeedupRatio is baseline_cost / candidate_cost. It is a model
// ratio, not a claim about wall-clock execution time. For example, 2 means
// half the modeled cost, not a guarantee that the query runs twice as fast.
PredictedSpeedupRatio float64 `json:"predicted_speedup_ratio,omitempty"`
// RowsReducedPercent is the modeled reduction in accumulated RowsExamined.
// It does not describe a reduction in rows returned to the caller.
RowsReducedPercent float64 `json:"rows_reduced_percent,omitempty"`
}
PredictedChange contains scale-independent changes between the internal baseline and candidate plans. These values are the preferred public summary because they do not mix native and internal absolute cost units.
type PreparedAnalysis ¶
type PreparedAnalysis struct {
// contains filtered or unexported fields
}
PreparedAnalysis bridges offline checks and online database evidence collection. Either Continue or the CollectOnlineSessionEvidence + CollectOnlineMetadata + FinishOnline sequence (or CollectOnlineEvidence + FinishOnline) consumes it at most once. Facts and rows are invocation-owned; callers must not mutate them or read them concurrently with online continuation.
func (*PreparedAnalysis) BindCanonicalizer ¶
func (p *PreparedAnalysis) BindCanonicalizer(c relation.Canonicalizer) error
BindCanonicalizer adopts observed server semantics before continuation. Static preparation uses case-preserving keys; online context construction rebinds the original AST. This method does not rerun completed syntax checks.
func (*PreparedAnalysis) CollectOnlineEvidence ¶
func (p *PreparedAnalysis) CollectOnlineEvidence(dbCtx *db.DBContext) error
CollectOnlineEvidence runs both session evidence collection and metadata loading against dbCtx, then freezes metadata DB access while retaining a read-only global cost config loader.
func (*PreparedAnalysis) CollectOnlineMetadata ¶
func (p *PreparedAnalysis) CollectOnlineMetadata() error
CollectOnlineMetadata builds the online AnalyzeContext against an unpinned pool handle (attached by the caller via dbCtx.AttachPool), binds the precollected EXPLAIN FORMAT=JSON result, and loads required table metadata and statistics through the shared layered cache singleflight.
func (*PreparedAnalysis) CollectOnlineSessionEvidence ¶
func (p *PreparedAnalysis) CollectOnlineSessionEvidence(dbCtx *db.DBContext) error
CollectOnlineSessionEvidence executes ONLY the session-dependent reads (traditional EXPLAIN, EXPLAIN FORMAT=JSON, and session-scoped @@optimizer_switch / @@SESSION.max_heap_table_size) on the caller's pinned connection and detaches that connection before returning so the caller can release it back to the pool immediately.
func (*PreparedAnalysis) Continue ¶
func (p *PreparedAnalysis) Continue(dbCtx *db.DBContext) (*OptimizeResult, error)
Continue runs online checks on a pinned connection using the original deadline. A non-nil result may accompany an error; callers must retain completed evidence.
func (*PreparedAnalysis) ExplainArtifact ¶
func (p *PreparedAnalysis) ExplainArtifact() ([]ExplainRow, error)
ExplainArtifact returns the traditional rows collected by Continue, without I/O.
func (*PreparedAnalysis) FinishOnline ¶
func (p *PreparedAnalysis) FinishOnline() (*OptimizeResult, error)
FinishOnline runs dynamic rules, post-processors, and whole-query what-if evaluation using the collected evidence. Table metadata reads are frozen; global cost constants (mysql.server_cost, mysql.engine_cost, sort_buffer_size) are loaded lazily at most once via sync.Once only if a cost consumer needs them.
func (*PreparedAnalysis) OnlineApplicable ¶
func (p *PreparedAnalysis) OnlineApplicable() bool
OnlineApplicable reports whether native plan and cost stages support this AST and SQL text safely under the read-only EXPLAIN boundary.
func (*PreparedAnalysis) OnlineEvidenceStatus ¶
func (p *PreparedAnalysis) OnlineEvidenceStatus() (metadata, explain string)
OnlineEvidenceStatus exposes collection outcomes without leaking driver errors.
func (*PreparedAnalysis) OnlineFactsAvailable ¶
func (p *PreparedAnalysis) OnlineFactsAvailable() bool
OnlineFactsAvailable reports whether Continue returned newly bound online facts, rather than its static fallback. Read it only after Continue has returned.
func (*PreparedAnalysis) ResetSessionCollectionForRetry ¶
func (p *PreparedAnalysis) ResetSessionCollectionForRetry() bool
ResetSessionCollectionForRetry clears session-stage state so the caller can retry CollectOnlineSessionEvidence on a fresh pinned connection after a transient broken-connection failure. It returns false once metadata collection or online finalization has begun.
func (*PreparedAnalysis) SessionExplainError ¶
func (p *PreparedAnalysis) SessionExplainError() error
SessionExplainError returns the native EXPLAIN error captured during CollectOnlineSessionEvidence, preferring EXPLAIN FORMAT=JSON over traditional EXPLAIN when both failed.
func (*PreparedAnalysis) StaticFacts ¶
func (p *PreparedAnalysis) StaticFacts() *OptimizeResult
StaticFacts returns the completed offline facts before continuation.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry 规则和后处理器的注册表
func DefaultRegistry ¶
func DefaultRegistry() *Registry
DefaultRegistry 返回包含全部已实现规则和后处理器的注册表。 规则选用(静态 / 动态 / 全部)由 RuleSet / RuleFilter 在分析时完成,不在此裁剪。
func (*Registry) AllRuleNames ¶
AllRuleNames 返回所有规则和子规则的完整名称
func (*Registry) PostProcessors ¶
func (r *Registry) PostProcessors() []PostProcessor
PostProcessors 返回所有未禁用的后处理器
func (*Registry) RegisterPostProcessor ¶
func (r *Registry) RegisterPostProcessor(pp PostProcessor)
RegisterPostProcessor 注册后处理器
type RejectedPlan ¶
type RejectedPlan struct {
// DesignFingerprint identifies the rejected physical-design scenario.
DesignFingerprint string `json:"design_fingerprint,omitempty"`
// SuggestionIDs lists suggestions included in the rejected scenario.
SuggestionIDs []string `json:"suggestion_ids,omitempty"`
// PlanDigest identifies the rejected internal plan.
PlanDigest string `json:"plan_digest,omitempty"`
// TotalCost is the rejected plan's internal whole-query cost.
TotalCost float64 `json:"total_cost,omitempty"`
// Reason explains why the plan did not win, such as higher cost or unused
// candidate indexes.
Reason string `json:"reason,omitempty"`
}
RejectedPlan explains why an evaluated physical design was not selected.
type RelationRef ¶
RelationRef identifies one physical relation without flattening its database.
type Rule ¶
type Rule interface {
// Name 返回规则名称(用于日志和调试)
Name() string
// SubRules 声明子规则名(用于发现和文档生成)
// 返回子名列表,不含父级前缀
SubRules() []string
// Requires 声明此规则的依赖
// RequiresAST: 仅需 AST(可在 AnalyzeStatic 中运行)
// RequiresExplain: 需要 Analyze 准备的 EXPLAIN 上下文
// RequiresBoth: 需要 AST + EXPLAIN
Requires() AnalyzerRequires
// Analyze 执行诊断并生成建议
Analyze(ctx *AnalyzeContext) *RuleResult
}
每个 Rule 端到端负责:诊断问题 + 生成建议
type RuleCheck ¶
type RuleCheck struct {
Name string
Requires AnalyzerRequires
// RequiresServerSemantics defers this check when identifier/version semantics are unprobed.
RequiresServerSemantics bool
}
RuleCheck declares the evidence required by one named check within a rule. Name is relative to the owning rule. Checks must honor IsEnabled when running.
type RuleChecks ¶
type RuleChecks interface {
Checks() []RuleCheck
}
RuleChecks supplies check-level dependencies for mixed rules. Rules without this interface inherit Requires for every SubRules entry.
type RuleDescriptor ¶
type RuleDescriptor struct {
Name string `json:"name"`
Parent string `json:"parent"`
Category IssueCategory `json:"category"`
Tags []string `json:"tags"`
StatementClasses []StatementClass `json:"statement_classes"`
DefaultSeverity analysis.Severity `json:"default_severity"`
Source AnalysisSource `json:"source"`
Requires AnalyzerRequires `json:"requires"`
IssueTypes []IssueType `json:"issue_types"`
}
func DefaultRuleCatalog ¶
func DefaultRuleCatalog() []RuleDescriptor
func FilterRules ¶
func FilterRules(c []RuleDescriptor, f RuleFilter) ([]RuleDescriptor, error)
type RuleFilter ¶
type RuleFilter struct {
Names []string
ExcludeNames []string
Categories []IssueCategory
Tags []string
StatementClasses []StatementClass
Severities []analysis.Severity
MinSeverity *analysis.Severity
Sources []AnalysisSource
Requires AnalyzerRequires
}
type RulePolicy ¶
type RulePolicy struct {
MaxIndexesPerTable int
DriverTableRowRatio float64
MaxJoinTables int
MaxGroupByColumnsNotice int
MaxGroupByColumnsWarning int
MaxOrderByColumnsNotice int
MaxOrderByColumnsWarning int
OrderByMaxColumnLength int64
MaxNestedSubqueryDepth int
MaxSubqueryCount int
MaxSQLLength int
MaxWhereInItems int
MaxLimitCount int64
LargeOffsetWarnThreshold int64
LargeOffsetErrorThreshold int64
ForbiddenFunctions []string
ExplainThresholds *ExplainThresholdConfig
DisabledRules map[string]bool
PriorityOverrides map[IssueType]int
}
RulePolicy configures MySQL rule selection and rule-specific thresholds. Cross-database row evidence belongs to analysis.DiagnosticPolicy.
func DefaultRulePolicy ¶
func DefaultRulePolicy() *RulePolicy
DefaultRulePolicy returns a fresh MySQL rule policy.
func (RulePolicy) Clone ¶
func (policy RulePolicy) Clone() RulePolicy
Clone returns a defensive deep copy of the rule policy.
func (RulePolicy) Resolve ¶
func (policy RulePolicy) Resolve() (RulePolicy, error)
Resolve validates, fills defaults, and returns a frozen-ready copy.
func (RulePolicy) Validate ¶
func (policy RulePolicy) Validate() error
Validate checks explicitly configured values. Zero means unspecified.
type RuleResult ¶
type RuleResult struct {
Rule string // Name of the producing rule.
Issues []*Issue // Diagnoses produced by this rule.
Opportunities []*OptimizationOpportunity `json:"-"`
// contains filtered or unexported fields
}
RuleResult separates diagnoses from independent design opportunities.
type RuleSet ¶
type RuleSet struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Rules []string `json:"rules"`
}
func BuiltinRuleSet ¶
BuiltinRuleSet returns a named subset of DefaultRuleCatalog. Registry stays complete; these names only choose what Analyze runs:
- "all": every implemented sub-rule
- "static": SourceAST rules, suitable for AnalyzeStatic
- "dynamic": SourceExplain rules; "plan" is a tag-based alias with the same members
func NewRuleSetFromFilter ¶
func NewRuleSetFromFilter(name string, f RuleFilter) (*RuleSet, error)
type SQLStyleRule ¶
type SQLStyleRule struct{}
SQLStyleRule SQL 写法规则 通过 AST 分析 SQL 写法问题,并生成改写建议
func (*SQLStyleRule) Analyze ¶
func (r *SQLStyleRule) Analyze(ctx *AnalyzeContext) *RuleResult
func (*SQLStyleRule) Name ¶
func (r *SQLStyleRule) Name() string
func (*SQLStyleRule) Requires ¶
func (r *SQLStyleRule) Requires() AnalyzerRequires
func (*SQLStyleRule) SubRules ¶
func (r *SQLStyleRule) SubRules() []string
type SortGroupRule ¶
type SortGroupRule struct{}
SortGroupRule 排序/分组规则 通过 EXPLAIN 结果分析排序和分组问题,并生成索引建议
func (*SortGroupRule) Analyze ¶
func (r *SortGroupRule) Analyze(ctx *AnalyzeContext) *RuleResult
func (*SortGroupRule) Checks ¶
func (r *SortGroupRule) Checks() []RuleCheck
Checks declares execution dependencies for each selectable check.
func (*SortGroupRule) Name ¶
func (r *SortGroupRule) Name() string
func (*SortGroupRule) Requires ¶
func (r *SortGroupRule) Requires() AnalyzerRequires
func (*SortGroupRule) SubRules ¶
func (r *SortGroupRule) SubRules() []string
type StatementClass ¶
type StatementClass string
const ( StatementClassDQL StatementClass = "DQL" StatementClassDML StatementClass = "DML" StatementClassDDL StatementClass = "DDL" )
type StatsTrace ¶
type StatsTrace struct {
// Database and Table identify the physical relation.
Database string `json:"database,omitempty"`
Table string `json:"table"`
// Source identifies the strongest statistics evidence used for the table.
Source string `json:"source"`
// Confidence is the 0..1 quality score assigned to that evidence.
Confidence float64 `json:"confidence,omitempty"`
// Version fingerprints the table statistics snapshot used for optimization.
Version string `json:"version,omitempty"`
}
StatsTrace identifies the strongest statistics source available for a table.
type SubqueryRule ¶
type SubqueryRule struct{}
SubqueryRule 子查询规则
func (*SubqueryRule) Analyze ¶
func (r *SubqueryRule) Analyze(ctx *AnalyzeContext) *RuleResult
func (*SubqueryRule) Checks ¶
func (r *SubqueryRule) Checks() []RuleCheck
Checks declares execution dependencies for each selectable check. Pure AST checks remain executable offline under AnalyzeStatic, while metadata- and EXPLAIN-backed checks declare RequiresMetadata so connected analysis loads table metadata before freezing the database handle.
func (*SubqueryRule) Name ¶
func (r *SubqueryRule) Name() string
func (*SubqueryRule) Requires ¶
func (r *SubqueryRule) Requires() AnalyzerRequires
func (*SubqueryRule) SubRules ¶
func (r *SubqueryRule) SubRules() []string
type SugAction ¶
type SugAction struct {
Type SuggestionType `json:"type"` // 操作类型
SQL string `json:"sql"` // 要执行的 SQL
Message string `json:"message"` // 操作说明
MessageRef *MessageRef `json:"message_ref,omitempty"` // 语言无关的操作说明引用
}
SugAction 单个优化操作
type Suggestion ¶
type Suggestion struct {
ID string `json:"id"`
IssueID string `json:"issue_id"`
Database string `json:"database,omitempty"`
Table string `json:"table"`
Message string `json:"message"`
Basis string `json:"basis"`
Actions []*SugAction `json:"actions"` // Action是AND关系
Reason string `json:"reason"`
Risk string `json:"risk"`
Priority int `json:"priority"`
MessageRef *MessageRef `json:"message_ref,omitempty"`
BasisRef *MessageRef `json:"basis_ref,omitempty"`
ReasonRefs []*MessageRef `json:"reason_refs,omitempty"`
RiskRef *MessageRef `json:"risk_ref,omitempty"`
Index *IndexSpec `json:"index,omitempty"`
Evidence *IndexEvidence `json:"evidence,omitempty"`
// 内部使用,不序列化
IndexColumns []string `json:"-"` // 建议索引的列(用于整查询 what-if 物理设计候选)
HintChanges []SuggestionHintChange `json:"-"`
// contains filtered or unexported fields
}
Suggestion 优化建议
func (*Suggestion) ActionTypesKey ¶
func (s *Suggestion) ActionTypesKey() string
ActionTypesKey 返回操作类型的组合键
func (*Suggestion) HasIndexAction ¶
func (s *Suggestion) HasIndexAction() bool
HasIndexAction 检查是否包含索引相关操作
type SuggestionHintChange ¶
type SuggestionHintChange struct {
HintID string
Operation HintChangeOperation
Table string
HintType string
HintScope string
IndexNames []string
}
SuggestionHintChange is structured, internal metadata for a query-hint rewrite. Whole-query what-if evaluation consumes this effect directly instead of parsing a localized message or generic REWRITE_SQL action.
type SuggestionType ¶
type SuggestionType string
SuggestionType 建议类型
const ( SugCreateIndex SuggestionType = "CREATE_INDEX" SugModifyIndex SuggestionType = "MODIFY_INDEX" SugDropIndex SuggestionType = "DROP_INDEX" SugCoveringIndex SuggestionType = "COVERING_INDEX" SugRemoveForce SuggestionType = "REMOVE_FORCE_INDEX" SugRemoveIgnore SuggestionType = "REMOVE_IGNORE_INDEX" SugChangeForce SuggestionType = "CHANGE_FORCE_INDEX" SugRewriteSQL SuggestionType = "REWRITE_SQL" SugChangeDataType SuggestionType = "CHANGE_DATA_TYPE" )
type TableIndexRule ¶
type TableIndexRule struct{}
TableIndexRule 动态索引规则
func (*TableIndexRule) Analyze ¶
func (r *TableIndexRule) Analyze(ctx *AnalyzeContext) *RuleResult
func (*TableIndexRule) Checks ¶
func (r *TableIndexRule) Checks() []RuleCheck
Checks declares execution dependencies for each selectable check.
func (*TableIndexRule) Name ¶
func (r *TableIndexRule) Name() string
func (*TableIndexRule) Requires ¶
func (r *TableIndexRule) Requires() AnalyzerRequires
func (*TableIndexRule) SubRules ¶
func (r *TableIndexRule) SubRules() []string
type TableStructure ¶
type TableStructure struct {
Database string `json:"database,omitempty"`
Table string `json:"table"`
CreateTableSQL string `json:"create_table_sql,omitempty"`
Status string `json:"status"`
Diagnostic *Diagnostic `json:"diagnostic,omitempty"`
// contains filtered or unexported fields
}
TableStructure contains the exact server definition used as schema context. SHOW CREATE TABLE collection is best-effort and never exposes table rows.
type ValidationTrace ¶
type ValidationTrace struct {
// Attempted reports whether baseline structural validation was possible.
Attempted bool `json:"attempted"`
// Matched reports whether every supported structural check passed.
Matched bool `json:"matched"`
// Reasons lists unavailable inputs or failed structural checks.
Reasons []string `json:"reasons,omitempty"`
}
ValidationTrace records structural validation between the modeled baseline and the native EXPLAIN plan.
type WhatIfCandidateIndex ¶
type WhatIfCandidateIndex struct {
SuggestionID string `json:"suggestion_id,omitempty"`
Database string `json:"database,omitempty"`
Table string `json:"table"`
Name string `json:"name"`
Columns []string `json:"columns"`
}
WhatIfCandidateIndex identifies a hypothetical index used by the evaluated candidate plan. It remains visible when the candidate is below the recommendation threshold so callers can explain what was compared.
type WhatIfEvaluation ¶
type WhatIfEvaluation struct {
// Status states whether evaluation completed and whether the selected
// candidate improved on the baseline. For NOT_EVALUABLE_* values, Baseline,
// Candidate, and Change contain zero values and must not be interpreted.
Status WhatIfStatus `json:"status"`
// Scope identifies the portion of the statement covered by the comparison.
// It is always WHOLE_QUERY in the current implementation.
Scope WhatIfScope `json:"scope"`
// Confidence is a 0..1 model-quality indicator derived from statistics quality
// and baseline alignment. It is not the probability that the query will be
// faster and should be considered together with Warnings and Unsupported.
Confidence float64 `json:"confidence,omitempty"`
// Model identifies the single cost model and unit shared by Baseline and
// Candidate. The two absolute costs are comparable only within this identity.
Model CostModelIdentity `json:"model"`
// Baseline is the internal planner's best legal plan under the current schema,
// indexes, and SQL hint constraints. It is not the native MySQL EXPLAIN plan.
Baseline ModelPlanEstimate `json:"baseline"`
// Candidate is the best internal plan after applying the selected hypothetical
// indexes and structured hint mutations. When no candidate is cheaper, the
// baseline plan is retained here.
Candidate ModelPlanEstimate `json:"candidate"`
// Change contains relative predictions computed only from the internal
// Baseline and Candidate estimates.
Change PredictedChange `json:"change"`
// Alignment reports structural agreement between the internal baseline and
// native EXPLAIN. It never converts or calibrates either cost space.
Alignment BaselineAlignment `json:"alignment"`
// PlanChanged reports whether Baseline and Candidate have different plan
// digests. It can be false even when candidate metadata was considered.
PlanChanged bool `json:"plan_changed,omitempty"`
// SelectedSuggestions contains stable suggestion IDs whose physical-design or
// hint mutations were retained by whole-query search.
SelectedSuggestions []string `json:"selected_suggestions,omitempty"`
// RejectedSuggestions contains one stable, suggestion-scoped explanation for
// every evaluated candidate that was not retained.
RejectedSuggestions []WhatIfSuggestionRejection `json:"rejected_suggestions,omitempty"`
// UsedSuggestedIndexes lists table-qualified hypothetical indexes actually
// used by Candidate. It is evidence about the evaluated plan and does not by
// itself mean that the index reached the recommendation threshold.
UsedSuggestedIndexes []string `json:"used_suggested_indexes,omitempty"`
// CandidateIndexes describes hypothetical indexes considered by the search,
// including candidates that were evaluated but not used or recommended.
CandidateIndexes []WhatIfCandidateIndex `json:"candidate_indexes,omitempty"`
// CandidateOutcome is the canonical evidence and decision record for the
// candidate pipeline. It is always present when WhatIf is present.
CandidateOutcome *CandidateOutcome `json:"candidate_outcome"`
// RecommendationThresholdPercent is the minimum (baseline/candidate-1)*100
// efficiency gain required before candidates become actionable recommendations.
RecommendationThresholdPercent float64 `json:"recommendation_threshold_percent,omitempty"`
// ConstraintChanges records selected structured SQL hint removals. It is the
// machine-readable counterpart of human-facing rewrite suggestions.
ConstraintChanges []ConstraintChangeTrace `json:"constraint_changes,omitempty"`
// BaselineConstraints and CandidateConstraints are deterministic fingerprints
// of the SQL hint constraints that define each legal plan space. Callers
// should compare them for equality rather than parse their contents.
BaselineConstraints string `json:"baseline_constraints,omitempty"`
CandidateConstraints string `json:"candidate_constraints,omitempty"`
// Warnings describes degraded statistics, baseline divergence, skipped
// candidates, and other conditions that reduce confidence without necessarily
// making the evaluation unusable. The strings follow the result language.
// WarningRefs keeps the language-neutral templates so RenderResult can
// refresh Warnings without re-running analysis.
Warnings []string `json:"warnings,omitempty"`
WarningRefs []*MessageRef `json:"warning_refs,omitempty"`
// Unsupported identifies SQL or plan features the internal model could not
// evaluate. Callers should treat a non-empty value as an explicit limitation.
// UnsupportedRefs is the language-neutral counterpart of Unsupported.
Unsupported []string `json:"unsupported,omitempty"`
UnsupportedRefs []*MessageRef `json:"unsupported_refs,omitempty"`
// Trace contains candidate-search, plan, statistics, validation, and cache
// diagnostics. It is populated only when EnableOptimizationTrace is enabled.
Trace *OptimizationTrace `json:"trace,omitempty"`
// contains filtered or unexported fields
}
WhatIfEvaluation is the canonical whole-query prediction for a hypothetical physical design. Callers must inspect Status before reading plan estimates. Baseline and Candidate always remain in the internal model space and must not be numerically compared with NativeExplainBaseline.QueryCost.
type WhatIfScope ¶
type WhatIfScope string
WhatIfScope identifies the portion of the SQL statement covered by a cost comparison.
const ( // ScopeWholeQuery means Baseline and Candidate include the complete statement, // including joins, subqueries, sorting, grouping, and other modeled operators. ScopeWholeQuery WhatIfScope = "WHOLE_QUERY" )
type WhatIfStatus ¶
type WhatIfStatus string
WhatIfStatus describes whether whole-query what-if evaluation completed and how the selected candidate compared with the baseline.
const ( StatusEvaluatedImproved WhatIfStatus = "EVALUATED_IMPROVED" // StatusEvaluatedNoChange means candidate mutations were retained but the // resulting internal total cost is effectively equal to the baseline. StatusEvaluatedNoChange WhatIfStatus = "EVALUATED_NO_CHANGE" // StatusEvaluatedLowImprovement means a cheaper candidate was evaluated, but // its estimated benefit did not reach the configured recommendation threshold. StatusEvaluatedLowImprovement WhatIfStatus = "EVALUATED_LOW_IMPROVEMENT" // StatusEvaluatedBaselineBest means evaluation succeeded but no candidate // beat the baseline, so Candidate contains the retained baseline plan. StatusEvaluatedBaselineBest WhatIfStatus = "EVALUATED_BASELINE_BEST" // StatusNotEvaluableNoCandidate means no supported index or hint mutation was // available for whole-query evaluation. StatusNotEvaluableNoCandidate WhatIfStatus = "NOT_EVALUABLE_NO_CANDIDATE" // StatusNotEvaluableUnsupported means the statement shape cannot currently be // represented by the internal logical or physical planner. StatusNotEvaluableUnsupported WhatIfStatus = "NOT_EVALUABLE_UNSUPPORTED_SQL" // StatusNotEvaluableRelationAmbiguous means native plan relations could not // be bound uniquely to physical relations. StatusNotEvaluableRelationAmbiguous WhatIfStatus = "NOT_EVALUABLE_RELATION_AMBIGUOUS" // StatusNotEvaluableStats means required metadata, statistics, or a valid // modeled plan was unavailable. StatusNotEvaluableStats WhatIfStatus = "NOT_EVALUABLE_STATS" // Public report statuses are emitted by the report projection path. StatusComplete WhatIfStatus = "COMPLETE" StatusPartial WhatIfStatus = "PARTIAL" StatusNotEvaluable WhatIfStatus = "NOT_EVALUABLE" )
type WhatIfSuggestionRejection ¶
type WhatIfSuggestionRejection struct {
SuggestionID string `json:"suggestion_id"`
Code WhatIfSuggestionRejectionCode `json:"code"`
Reason string `json:"reason"`
ReasonRef *MessageRef `json:"reason_ref,omitempty"`
Evidence *IndexEvidence `json:"evidence,omitempty"`
}
WhatIfSuggestionRejection explains why a candidate generated by the rule layer was not retained by whole-query search. Evidence remains language-neutral; Reason and ReasonRef provide a user-facing explanation that can be rendered again without re-running analysis.
type WhatIfSuggestionRejectionCode ¶
type WhatIfSuggestionRejectionCode string
WhatIfSuggestionRejectionCode is a stable machine-readable explanation for why one evaluated physical-design suggestion was not recommended.
const ( WhatIfRejectionCandidateIndexNotUsed WhatIfSuggestionRejectionCode = "CANDIDATE_INDEX_NOT_USED" WhatIfRejectionLowCardinalityIndexNotUsed WhatIfSuggestionRejectionCode = "LOW_CARDINALITY_CANDIDATE_INDEX_NOT_USED" WhatIfRejectionBaselineCostNotImproved WhatIfSuggestionRejectionCode = "BASELINE_COST_NOT_IMPROVED" WhatIfRejectionBelowRecommendationThreshold WhatIfSuggestionRejectionCode = "BELOW_RECOMMENDATION_THRESHOLD" WhatIfRejectionSuperseded WhatIfSuggestionRejectionCode = "SUPERSEDED" WhatIfRejectionEvaluationFailed WhatIfSuggestionRejectionCode = "EVALUATION_FAILED" WhatIfRejectionCandidateNotSelected WhatIfSuggestionRejectionCode = "CANDIDATE_NOT_SELECTED" )
type WhereAuditRule ¶
type WhereAuditRule struct{}
WhereAuditRule WHERE 条件审计规则(从 rule_handler_where.go 迁移) 覆盖以下检查:
- no_where: SELECT 无 WHERE
- like_fuzzy_match: LIKE 前导通配符
- like_no_wildcard: LIKE 无通配符
- compare_null: column = NULL
- or_diff_table: OR 引用不同表
- op_on_column: 条件列上有函数/运算
- index_invalid_not: NOT 操作符
- index_invalid_op: 索引列上函数/运算失效 (需 DB)
- check_has_index: WHERE 未命中索引 (需 DB)
- check_index_val_type: 索引列值类型不匹配 (需 DB)
- combine_index_leftmost: 联合索引最左前缀 (需 DB)
谓词形态和索引访问子规则遍历 WhereDNF。 no_where / or_diff_table / compare_null / like_no_wildcard 仍走原始 WHERE AST, 因为 DNF 会拆掉或误分类这些事实。
func (*WhereAuditRule) Analyze ¶
func (r *WhereAuditRule) Analyze(ctx *AnalyzeContext) *RuleResult
func (*WhereAuditRule) Checks ¶
func (r *WhereAuditRule) Checks() []RuleCheck
Checks declares execution dependencies for each selectable check.
func (*WhereAuditRule) Name ¶
func (r *WhereAuditRule) Name() string
func (*WhereAuditRule) Requires ¶
func (r *WhereAuditRule) Requires() AnalyzerRequires
func (*WhereAuditRule) SubRules ¶
func (r *WhereAuditRule) SubRules() []string
Source Files
¶
- candidate_scenarios.go
- candidate_sources.go
- context.go
- cte_semantics.go
- diagnostic_coordinator.go
- diagnostic_coordinator_join.go
- diagnostic_coordinator_sort.go
- diagnostic_policy.go
- explain.go
- explain_support.go
- global_cost.go
- global_search.go
- helpers.go
- index_opportunity.go
- index_patterns.go
- localization.go
- messages.go
- opportunity.go
- optimizer.go
- prepared_analysis.go
- registry.go
- report_candidate_reasons.go
- report_candidate_scenarios.go
- report_opportunity_issue.go
- report_public.go
- report_public_advice.go
- report_public_projection.go
- report_scenario.go
- report_table_snapshot.go
- result_model.go
- rule_cte.go
- rule_dependencies.go
- rule_dml.go
- rule_groupby_orderby.go
- rule_helpers.go
- rule_index.go
- rule_index_new.go
- rule_index_optimize.go
- rule_join.go
- rule_join_static.go
- rule_sort_group.go
- rule_sql_style.go
- rule_subquery.go
- rule_where.go
- rule_where_dnf.go
- rule_where_helpers.go
- ruleset.go
- table_capability.go
- types.go
- whatif_diagnostics.go