optimizer

package
v0.4.0 Latest Latest
Warning

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

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnalyzeCriticalDDL

func AnalyzeCriticalDDL(statement *parser.DDLStatement, catalog *pgdb.DDLCatalog, language string, messages *sqli18n.Catalog) []*analysis.Issue

AnalyzeCriticalDDL runs the six destructive DDL rules. Catalog may be nil; AST-proven intent is still reported while catalog-dependent detail is marked unknown. The function never renders an action.

func AnalyzeCriticalDDLBatch

func AnalyzeCriticalDDLBatch(batch *parser.DDLBatch, catalog *pgdb.DDLCatalog, language string, messages *sqli18n.Catalog) []*analysis.Issue

AnalyzeCriticalDDLBatch reviews an ordered migration script. It never executes SQL. Analyze and AnalyzeDDL remain one-statement.

func AnalyzeCriticalDDLBatchWithPolicies

func AnalyzeCriticalDDLBatchWithPolicies(batch *parser.DDLBatch, catalog *pgdb.DDLCatalog, language string, messages *sqli18n.Catalog, rulePolicy RulePolicy, diagnosticPolicy analysis.DiagnosticPolicy) []*analysis.Issue

AnalyzeCriticalDDLBatchWithPolicies reviews an ordered migration script using immutable rule and diagnostic policy snapshots. It never executes SQL.

func AnalyzeCriticalDDLWithPolicies

func AnalyzeCriticalDDLWithPolicies(statement *parser.DDLStatement, catalog *pgdb.DDLCatalog, language string, messages *sqli18n.Catalog, rulePolicy RulePolicy, diagnosticPolicy analysis.DiagnosticPolicy) []*analysis.Issue

AnalyzeCriticalDDLWithPolicies reviews one DDL statement using immutable rule and diagnostic policy snapshots.

func AnalyzeStatic

func AnalyzeStatic(statement *parser.Statement, language string) []*analysis.Issue

AnalyzeStatic runs the PostgreSQL AST-only rules with English fallback.

func AnalyzeStaticWithCatalog

func AnalyzeStaticWithCatalog(statement *parser.Statement, language string, catalog *sqli18n.Catalog) []*analysis.Issue

AnalyzeStaticWithCatalog runs only rules whose evidence is SQL text/AST.

func AnalyzeStaticWithCatalogAndPolicies

func AnalyzeStaticWithCatalogAndPolicies(statement *parser.Statement, language string, catalog *sqli18n.Catalog, rulePolicy RulePolicy, diagnosticPolicy analysis.DiagnosticPolicy) []*analysis.Issue

AnalyzeStaticWithCatalogAndPolicies runs AST rules with immutable rule and diagnostic policy snapshots.

func CriticalDDLMetadataFailureDescription

func CriticalDDLMetadataFailureDescription(messages *sqli18n.Catalog, language string) string

CriticalDDLMetadataFailureDescription localizes the non-fatal connected catalog degradation used by AnalysisAgent.AnalyzeDDL.

func CriticalDDLUnsupportedDescription

func CriticalDDLUnsupportedDescription(messages *sqli18n.Catalog, language, node string) string

CriticalDDLUnsupportedDescription localizes the explicit degradation for an ALTER TABLE subcommand outside the critical-rule model.

func DescribeIndexRecommendationIssue

func DescribeIndexRecommendationIssue(issue *analysis.Issue, catalog *sqli18n.Catalog, language string) *analysis.Issue

DescribeIndexRecommendationIssue fills the description and description reference of the aggregate PG.INDEX_RECOMMENDATION issue that carries index candidates produced outside a rule context.

func NeedsSpecialIndexCapabilities

func NeedsSpecialIndexCapabilities(s *parser.Statement) bool

NeedsSpecialIndexCapabilities avoids additional catalog I/O on ordinary SQL.

func NewMessageRef

func NewMessageRef(message *goi18n.Message, args map[string]any) *analysis.MessageRef

NewMessageRef persists the stable template identity, English fallback text, and a defensive copy of the language-neutral template arguments. Copying the arguments keeps a concurrent renderer from observing a caller mutation.

func RenderCreateIndex

func RenderCreateIndex(design CandidateDesign) (string, error)

RenderCreateIndex renders executable PostgreSQL DDL from a safe structured B-tree design. It never performs SQL string substitution on user SQL.

func RenderMessage

func RenderMessage(catalog *sqli18n.Catalog, lang string, ref *analysis.MessageRef) string

func RenderResult

func RenderResult(result *analysis.AnalyzeResult, catalog *sqli18n.Catalog, lang string) *analysis.AnalyzeResult

RenderResult re-renders every message-backed field of an analysis result in the requested language and records that language on the copy. The caller's result, issues, suggestions, and actions are treated as concurrently readable shared data and are never mutated in place. Fields without a reference keep their existing text.

func SortIndexCandidates

func SortIndexCandidates(candidates []IndexCandidate)

SortIndexCandidates orders results independently of discovery maps.

func ValidateCandidateColumns

func ValidateCandidateColumns(design CandidateDesign, table TableModel) error

ValidateCandidateColumns ensures every key and INCLUDE column exists.

Types

type AccessMethod

type AccessMethod string

AccessMethod identifies a PostgreSQL index access method.

const (

	// AccessMethodBTree is the fully recommended access method in the first
	// PostgreSQL implementation.
	AccessMethodBTree AccessMethod = "btree"
	// AccessMethodGIN is recognized but not automatically rendered.
	AccessMethodGIN AccessMethod = "gin"
	// AccessMethodGiST is recognized but not automatically rendered.
	AccessMethodGiST AccessMethod = "gist"
	// AccessMethodSPGiST is recognized but not automatically rendered.
	AccessMethodSPGiST AccessMethod = "spgist"
	// AccessMethodBRIN is recognized but not automatically rendered.
	AccessMethodBRIN AccessMethod = "brin"
	// AccessMethodHash is recognized but not automatically rendered.
	AccessMethodHash AccessMethod = "hash"
)

type AnalyzeContext

type AnalyzeContext struct {
	// DefaultSchema is caller-declared static namespace context, never catalog proof.
	DefaultSchema string
	Statement     *parser.Statement
	Bound         *parser.BoundStatement
	Relations     []*pgdb.Relation
	Plan          *explain.NativePlan
	Language      string
	Catalog       *sqli18n.Catalog
	// DiagnosticPolicy is the request-frozen Agent policy. A zero value uses
	// the registry's immutable default snapshot.
	DiagnosticPolicy analysis.DiagnosticPolicy
	// SpecialIndexes is uncached, request-local catalog proof for special DDL.
	SpecialIndexes *pgdb.SpecialIndexCapabilities
	// BuiltinOperatorsVisible proves pg_catalog is first in the captured effective
	// search path. It does not prove arbitrary overloaded function resolution.
	BuiltinOperatorsVisible bool
}

AnalyzeContext contains PostgreSQL-owned syntax, binding, catalog, plan, and localization evidence. Rules declare the minimum evidence they consume.

type CandidateDesign

type CandidateDesign struct {
	Name         string
	Schema       string
	Table        string
	AccessMethod AccessMethod
	Keys         []IndexColumn
	Include      []string
	Predicate    string
	Expression   string
}

CandidateDesign is a PostgreSQL structured physical design.

func (CandidateDesign) Identity

func (design CandidateDesign) Identity() string

Identity identifies a physical design independently of the displayed DDL name.

type CheckedRule

type CheckedRule interface {
	Rule
	Checks() []RuleCheck
}

CheckedRule optionally declares executable checks with distinct dependencies. When Checks is nonempty, the registry schedules those callbacks and never calls the parent's Analyze. Ordinary advice SubRules are not executable checks.

type ColumnModel

type ColumnModel struct {
	Name         string
	Type         string
	NDistinct    float64
	AverageWidth int32
	Collation    string
}

ColumnModel contains recommendation inputs independent of current literals.

type IndexCandidate

type IndexCandidate struct {
	Design     CandidateDesign
	Safe       bool
	Reason     string
	Suggestion *analysis.Suggestion
	Diagnostic analysis.Diagnostic
	// contains filtered or unexported fields
}

IndexCandidate pairs a design with safety and public recommendation output.

func GenerateIndexCandidates

func GenerateIndexCandidates(input RecommendationInput) []IndexCandidate

GenerateIndexCandidates produces at most one deterministic B-tree design for a single relation workload shape.

func (IndexCandidate) SourceOccurrences

func (c IndexCandidate) SourceOccurrences() []IndexCandidateSource

SourceOccurrences returns the physical references and their CTE paths.

func (IndexCandidate) SourceReferences

func (c IndexCandidate) SourceReferences() []parser.RelationRef

SourceReferences returns the physical SQL occurrences used to generate this candidate. Actual use is determined separately by the PostgreSQL planner.

func (*IndexCandidate) SuggestionLanguage

func (c *IndexCandidate) SuggestionLanguage(catalog *sqli18n.Catalog, language string)

SuggestionLanguage materializes the summary, reason, and DDL explanation of a candidate with the requested language while keeping the stable template references. A nil language keeps the English template text, which is the language-neutral default for catalog-free index candidate generation.

type IndexCandidateSource

type IndexCandidateSource struct {
	Reference      parser.RelationRef
	OccurrencePath string
	// PredicateSources records only proven input operands, not native adoption.
	PredicateSources []analysis.PredicateSource
}

IndexCandidateSource relates a candidate to a physical SQL reference. OccurrencePath distinguishes inline CTE consumers. Its segments are /<query block ID>@<byte offset of the CTE reference>, innermost first.

type IndexColumn

type IndexColumn struct {
	Name      string
	Direction SortDirection
	Nulls     NullOrdering
}

IndexColumn is one structured B-tree key.

type IndexModel

type IndexModel struct {
	Name            string
	AccessMethod    AccessMethod
	Valid           bool
	Keys            []IndexColumn
	Include         []string
	Predicate       string
	Expression      string
	OperatorClasses []string
	Collations      []string
}

IndexModel is the PostgreSQL optimizer's independent existing-index model.

type NullOrdering

type NullOrdering string

NullOrdering is PostgreSQL B-tree NULL placement.

const (
	// NullsFirst places NULL values before non-NULL values.
	NullsFirst NullOrdering = "NULLS FIRST"
	// NullsLast places NULL values after non-NULL values.
	NullsLast NullOrdering = "NULLS LAST"
)

type PreparedAnalysis

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

PreparedAnalysis retains completed syntax checks for exactly one continuation. StaticFacts and the supplied AST are invocation-owned; do not mutate or read them concurrently with Continue. No method opens a database connection.

func (*PreparedAnalysis) Continue

func (p *PreparedAnalysis) Continue(evidence *AnalyzeContext) ([]*analysis.Issue, error)

Continue consumes the preparation and runs pending online checks with the original context. A non-nil result accompanying an error retains prior facts.

func (*PreparedAnalysis) PendingRequirements

func (p *PreparedAnalysis) PendingRequirements() []Requirement

PendingRequirements reports the distinct dependencies of uncompleted, enabled checks. Callers that opt into selected-rule evidence collection can avoid unused sources; the Agent's default complete-report policy is unchanged. Static enrichers consume already available evidence and do not request extra sources merely because a syntax finding exists.

func (*PreparedAnalysis) StaticFacts

func (p *PreparedAnalysis) StaticFacts() []*analysis.Issue

StaticFacts returns the completed, deterministically ordered syntax findings.

type RecommendationInput

type RecommendationInput struct {
	Table                 TableModel
	LookupEqualityColumns []string
	EqualityColumns       []string
	RangeColumns          []string
	OrderColumns          []IndexColumn
	ProjectionColumns     []string
	PreferredAccessMethod AccessMethod
	PartialPredicate      string
	PredicateProvenStable bool
	Expression            string
	ExpressionImmutable   bool
}

RecommendationInput is a value-independent workload shape. Literal values are intentionally absent so they cannot alter persistent index design.

type Registry

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

Registry stores PostgreSQL rules in stable name order.

func NewDefaultRegistry

func NewDefaultRegistry() *Registry

NewDefaultRegistry returns the initial PostgreSQL static/dynamic rules.

func NewDefaultRegistryWithPolicies

func NewDefaultRegistryWithPolicies(rulePolicy RulePolicy, diagnosticPolicy analysis.DiagnosticPolicy) *Registry

NewDefaultRegistryWithPolicies returns the PostgreSQL rules configured from immutable rule and diagnostic policy snapshots.

func NewRegistry

func NewRegistry(rules ...Rule) *Registry

NewRegistry constructs a registry without relying on registration order.

func (*Registry) Analyze

func (registry *Registry) Analyze(ctx *AnalyzeContext) []*analysis.Issue

Analyze runs rules whose required evidence is available, then deduplicates root causes and sorts stable semantic keys.

func (*Registry) Catalog

func (registry *Registry) Catalog() []RuleDescriptor

Catalog returns independent selectable parent/check descriptors and their actual dependencies. Ordinary advice subrules retain their parent dependency.

func (*Registry) PrepareAnalysis

func (registry *Registry) PrepareAnalysis(ctx context.Context, evidence *AnalyzeContext) (*PreparedAnalysis, error)

PrepareAnalysis executes syntax checks once, retaining completed work even when cancellation interrupts later checks. The caller owns parsing and I/O.

func (*Registry) Validate

func (registry *Registry) Validate() error

Validate reports invalid executable-check definitions before any analysis or I/O. NewRegistry retains construction errors for this method and preparation.

func (*Registry) WithPolicies

func (registry *Registry) WithPolicies(rules RulePolicy, diagnostics analysis.DiagnosticPolicy) *Registry

WithPolicies returns an independent registry with frozen policies and the same immutable rule implementations. Rule instances must be safe for use by concurrent requests, just as they must be when supplied to NewRegistry.

func (*Registry) WithRuleSelection

func (registry *Registry) WithRuleSelection(names []string) (*Registry, error)

WithRuleSelection returns an immutable request-specific subset. Nil keeps the configured defaults; an explicit empty slice selects no rules. Existing disabled-rule policy remains authoritative, including for selected subrules.

type RelationCandidates

type RelationCandidates struct {
	Relation   *pgdb.Relation
	Candidates []IndexCandidate
}

RelationCandidates groups deterministic candidates by resolved relation.

func GenerateStatementIndexAlternatives

func GenerateStatementIndexAlternatives(statement *parser.Statement, bound *parser.BoundStatement, relations []*pgdb.Relation) []RelationCandidates

GenerateStatementIndexAlternatives explores B-tree designs separately for each proven SELECT relation occurrence, including paths through inline CTEs. Identical physical designs are merged before evaluation.

func GenerateStatementIndexCandidates

func GenerateStatementIndexCandidates(statement *parser.Statement, bound *parser.BoundStatement, relations []*pgdb.Relation) []RelationCandidates

GenerateStatementIndexCandidates maps PostgreSQL AST column shapes and immutable catalog snapshots into persistent, literal-independent designs.

type Requirement

type Requirement string

Requirement declares the evidence a PostgreSQL rule consumes.

const (
	// RequiresAST is safe for offline static analysis.
	RequiresAST Requirement = "AST"
	// RequiresMetadata consumes AST and collected catalog facts, without a plan.
	RequiresMetadata Requirement = "METADATA"
	// RequiresExplain consumes only PostgreSQL NativePlan facts.
	RequiresExplain Requirement = "EXPLAIN"
	// RequiresBoth consumes PostgreSQL AST and NativePlan evidence.
	RequiresBoth Requirement = "BOTH"
)

type Rule

type Rule interface {
	Name() string
	SubRules() []string
	Requirements() Requirement
	Analyze(*AnalyzeContext) []*analysis.Issue
}

Rule is the PostgreSQL-specific rule contract.

func NewCTEScanHighLoopsRule

func NewCTEScanHighLoopsRule() Rule

func NewCardinalityMisestimateRule

func NewCardinalityMisestimateRule() Rule

NewCardinalityMisestimateRule compares estimated and actual rows per loop, requiring at least a 10x ratio and a 1,000-row absolute gap. A denominator floor of one avoids overstating ratios for zero or rounded row averages. Known early-stop contexts, subplans, and non-tuple bitmap nodes are excluded.

func NewGatherSingleNodeBottleneckRule

func NewGatherSingleNodeBottleneckRule() Rule

func NewHashBatchSpillRule

func NewHashBatchSpillRule() Rule

NewHashBatchSpillRule reports executed Hash nodes with more than one runtime batch, or hashed/mixed Aggregate nodes with multiple HashAgg batches or positive Disk Usage. Original Hash Batches and inclusive temp I/O are ignored.

func NewHighSharedBufferReadsRule

func NewHighSharedBufferReadsRule() Rule

func NewHighTempIORule

func NewHighTempIORule() Rule

func NewInefficientIndexFilterRule

func NewInefficientIndexFilterRule() Rule

NewInefficientIndexFilterRule reports index scans discarding at least 90% of observed rows and at least 1,000 rows across loops. This proves residual-filter work, not poor table-relative index selectivity, which requires catalog data.

func NewJoinFilterDiscardsManyRule

func NewJoinFilterDiscardsManyRule() Rule

func NewLossyBitmapRecheckRule

func NewLossyBitmapRecheckRule() Rule

NewLossyBitmapRecheckRule reports bitmap heap scans with positive lossy blocks and at least 1,000 rows removed by index recheck across execution loops.

func NewNestedLoopRepeatedScanRule

func NewNestedLoopRepeatedScanRule() Rule

NewNestedLoopRepeatedScanRule reports scans beneath a Nested Loop inner branch with at least 10 actual loops and at least 1,000 observed rows examined per loop. Materialize/Memoize loop counts are never assigned to their children.

func NewRowsRemovedByFilterRule

func NewRowsRemovedByFilterRule() Rule

func NewSortDiskSpillRule

func NewSortDiskSpillRule() Rule

NewSortDiskSpillRule reports executed Sort nodes with an external sort method or positive disk sort space. Inclusive temp I/O alone is not spill evidence. Worker-only and Incremental Sort group statistics are deliberately excluded.

func NewSubplanHighLoopsRule

func NewSubplanHighLoopsRule() Rule

NewSubplanHighLoopsRule reports SubPlan/InitPlan roots with at least 100 actual loops and at least 1,000 ms cumulative node time (per-loop time times loops). Timing-disabled plans are skipped. Repetition does not establish correlation, and cumulative inclusive node time is not whole-query wall-clock duration.

func NewTriggerExecutionOverheadRule

func NewTriggerExecutionOverheadRule() Rule

func QueryAccessRules

func QueryAccessRules() []Rule

QueryAccessRules returns the combined PostgreSQL query access diagnostics.

func QueryDMLRules

func QueryDMLRules() []Rule

QueryDMLRules returns DQL/DML warning rules in stable factory order.

func QueryExpressionRules

func QueryExpressionRules() []Rule

QueryExpressionRules returns query-expression review rules in stable factory order.

func QueryGroupingRules

func QueryGroupingRules() []Rule

QueryGroupingRules returns the catalog-gated GROUP BY and HAVING rules.

func QueryJoinRules

func QueryJoinRules() []Rule

QueryJoinRules returns the catalog-backed query/join review rules.

type RuleCheck

type RuleCheck struct {
	Name     string
	Requires Requirement
	Analyze  func(*AnalyzeContext) []*analysis.Issue
}

RuleCheck is one independently scheduled check of a registered parent rule. Name may be relative to the parent or its fully qualified child name. Analyze must be safe for concurrent requests, like Rule.Analyze.

type RuleDescriptor

type RuleDescriptor struct {
	Name     string      `json:"name"`
	Parent   string      `json:"parent,omitempty"`
	Tags     []string    `json:"tags"`
	Requires Requirement `json:"requires"`
}

RuleDescriptor describes a selectable PostgreSQL rule or advice subrule. Requires states its actual minimum evidence, independently of its tags.

func DefaultRuleCatalog

func DefaultRuleCatalog() []RuleDescriptor

DefaultRuleCatalog returns independent descriptors in stable name order. Index recommendation is an Agent stage and is included explicitly.

type RulePolicy

type RulePolicy struct {
	DisabledRules      map[string]bool
	ForbiddenFunctions []string
	PriorityOverrides  map[string]int

	OrderByWideMinimumWidth           int32
	PartitionPruningMinimumPartitions int
	PartitionPruningMinimumFraction   float64
	PoorIndexScanMinimumFraction      float64
	HashJoinBuildMinimumBytes         int64
	DMLAffectedRowsMaximum            int64
	InListMaximumItems                int
	SQLMaximumBytes                   int
	GroupByNoticeThreshold            int
	GroupByWarningThreshold           int
	OrderByNoticeThreshold            int
	OrderByWarningThreshold           int
	SubqueryMaximumCount              int
	SubqueryMaximumDepth              int
	MaximumRelations                  int
	InsertMaximumRows                 int
	OffsetPaginationMaximum           int64
	LimitMaximumCount                 int64
	LargeOffsetWarningThreshold       int64
	LargeOffsetCriticalThreshold      int64
	HighCostSubplanMinimumCost        float64
	FilterColumnMaximumFraction       float64
	LateralOuterMinimumRows           int64
	InsertSelectRowsMaximum           int64
	IndexCountMaximum                 int
	IndexKeyMaximum                   int
	IndexIncludeMaximum               int
	PartitionCountMaximum             int
	IdentityInt2Rows                  float64
	IdentityInt4Rows                  float64
	DefaultPartitionMinimumShare      float64
	IdentifierMaximumBytes            int
}

RulePolicy configures PostgreSQL rule selection, rule-specific thresholds, forbidden functions, and final suggestion priorities. Cross-database row evidence thresholds belong to analysis.DiagnosticPolicy.

func DefaultRulePolicy

func DefaultRulePolicy() RulePolicy

DefaultRulePolicy returns a fresh PostgreSQL rule policy.

func (RulePolicy) Clone

func (policy RulePolicy) Clone() RulePolicy

Clone returns a defensive deep copy.

func (RulePolicy) Resolve

func (policy RulePolicy) Resolve() (RulePolicy, error)

Resolve validates and fills zero values from the defaults.

func (RulePolicy) Validate

func (policy RulePolicy) Validate() error

Validate checks explicitly configured values. Zero means unspecified.

type RuleSet

type RuleSet struct {
	Name  string   `json:"name"`
	Rules []string `json:"rules"`
}

RuleSet is an immutable-by-convention named selection of rule identifiers.

func BuiltinRuleSet

func BuiltinRuleSet(name string) (*RuleSet, error)

BuiltinRuleSet returns all, static, dynamic or plan (an alias of dynamic). Static selects syntax-only checks; dynamic includes catalog-dependent rules.

type SortDirection

type SortDirection string

SortDirection is a PostgreSQL B-tree key direction.

const (
	// DirectionAsc is ascending B-tree order.
	DirectionAsc SortDirection = "ASC"
	// DirectionDesc is descending B-tree order.
	DirectionDesc SortDirection = "DESC"
)

type StaticEnricher

type StaticEnricher interface {
	EnrichStatic(*AnalyzeContext, []*analysis.Issue) []*analysis.Issue
}

StaticEnricher augments already completed syntax findings with online facts. It must not rerun the syntax checks or mutate shared rule-owned state.

type TableModel

type TableModel struct {
	Schema          string
	Name            string
	Columns         []ColumnModel
	ExistingIndexes []IndexModel
}

TableModel contains the stable schema facts used to design an index.

Source Files

Jump to

Keyboard shortcuts

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