Documentation
¶
Overview ¶
Package analysis defines the stable, engine-neutral API contract for SQL analysis. Database parsers, plans, metadata, rules, caches, and cost models remain in their engine packages.
Index ¶
- Constants
- func EvidenceID(kind, key string) string
- func SemanticID(kind string, parts ...string) string
- func TableID(engine Engine, schema, name string) string
- type AccessMethodChange
- type AccessProperties
- type Action
- type ActionDefinition
- type ActionExecution
- type ActionPayload
- type ActionPrecondition
- type ActionType
- type Agent
- type AnalysisContext
- type AnalysisError
- type AnalysisStage
- type AnalysisStatus
- type AnalysisSummary
- type AnalyzeResult
- type AssessmentReport
- type BenefitAssessment
- type BenefitScope
- type CandidateCost
- type CandidateReport
- type CapabilityID
- type CapabilityStatus
- type CapabilitySupport
- type CheckRecord
- type CollectionCount
- type ColumnDefinition
- type ColumnStatistics
- type Confidence
- type ConstraintDefinition
- type CostEstimate
- type CostInterpretation
- type CostLimitationCode
- type CostModelIdentity
- type CostProvider
- type CostScope
- type CoverageReport
- type DebugEvent
- type DebugTraceReport
- type DecisionRecord
- type Diagnostic
- type DiagnosticCode
- type DiagnosticPolicy
- type DiagnosticReport
- type DiagnosticThresholds
- type DispositionCount
- type Engine
- type ErrorCode
- type EstimatedAccess
- type EstimatedPlan
- type EstimatedPlanInput
- type EstimatedPlanNode
- type EvaluationAlternative
- type EvaluationComparison
- type EvaluationContext
- type EvaluationReport
- type EvaluationScenario
- type EvidenceRecord
- type EvidenceRef
- type ExecutionReport
- type ExecutionStage
- type ExplainFieldAnalysis
- type ExplainFieldResult
- type ExplainResult
- type FindingFact
- type IndexDefinition
- type IndexKeyPart
- type IndexStatistics
- type Issue
- type IssueAdvice
- type IssueSource
- type JoinProperties
- type LegacyAnalyzeResult
- type LegacyOptimizeResult
- type Location
- type LogicalRewriteAttempt
- type LogicalRewriteCostComparison
- type LogicalRewriteDiff
- type LogicalRewriteReport
- type Message
- type MessageRef
- type Metric
- type MetricComparison
- type MySQLIndexProperties
- type NativeAccess
- type NativeExplainRow
- type NativeExplainSummary
- type NativePlanReport
- type NativeRelationAccess
- type NextAction
- type NodeEstimates
- type NodeMatch
- type Notice
- type ObservationCount
- type Omission
- type PlanChange
- type PlanSummary
- type PolicyFact
- type PostgreSQLIndexProperties
- type PredicateSource
- type RationaleClaim
- type RawMySQLAccess
- type RawMySQLCostChange
- type RawMySQLCostModelIdentity
- type RawMySQLDiagnostic
- type RawMySQLIndexKeyPart
- type RawMySQLIndexSpec
- type RawMySQLIssue
- type RawMySQLNativePlan
- type RawMySQLPlan
- type RawMySQLRejectedSuggestion
- type RawMySQLRelationRef
- type RawMySQLStructure
- type RawMySQLSuggestion
- type RawMySQLWhatIf
- type RawMySQLWhatIfWarning
- type Reason
- type Recommendation
- type RecommendationBenefit
- type RecommendationDecision
- type RecommendationPolicyCheck
- type RecommendationPriority
- type RecommendationProvenance
- type RecommendationRationale
- type RecommendationRelation
- type RecommendationTradeoffs
- type RecommendationValidation
- type RecommendedAction
- type RecordedIndexCandidate
- type RecordedNativeAccess
- type Recording
- type RecordingReport
- type RelationIdentity
- type RelationRef
- type RelativeModelCost
- type Report
- type RequestOption
- type RequestOptions
- type Result
- type RewriteAttemptDiagnostic
- type RewriteDefinition
- type SQLTarget
- type ScenarioChange
- type ServerVersion
- type Severity
- type SeverityPolicy
- type SubjectRef
- type Suggestion
- type SuggestionType
- type TableProperties
- type TableReference
- type TableSnapshot
- type TableStatistics
- type TableStructure
- type TradeoffEstimate
- type TradeoffItem
- type UsedIndexesChange
- type ValidationRecord
- type VerificationStep
- type VersionProfile
- type WhatIfEvaluation
- type WhatIfStatus
Constants ¶
const ( // ExecutionStatusCompleted means the execution or stage completed. ExecutionStatusCompleted = "COMPLETED" // ExecutionStatusPartial means the execution or stage is incomplete. ExecutionStatusPartial = "PARTIAL" // ExecutionStatusFailed means the execution or stage failed. ExecutionStatusFailed = "FAILED" // ExecutionStatusSkipped means a stage was not run; it is not an overall status. ExecutionStatusSkipped = "SKIPPED" // ExecutionStatusNotApplicable means a stage does not apply; it is not an overall status. ExecutionStatusNotApplicable = "NOT_APPLICABLE" )
const ( // ReportStatusAvailable means a usable report exists, not that SQL execution is authorized. ReportStatusAvailable = "AVAILABLE" // ReportStatusNotAvailable means no usable report was produced. ReportStatusNotAvailable = "NOT_AVAILABLE" // ReportStatusInvalid means the produced report failed validation. ReportStatusInvalid = "INVALID" )
const ( // BindingUnresolved marks syntax whose physical binding is not proven. BindingUnresolved = "UNRESOLVED" // StructureNotCollected marks metadata that was not collected. StructureNotCollected = "NOT_COLLECTED" MetricUnavailable = "UNAVAILABLE" )
const ReportSchemaVersion = "analysis/v2"
ReportSchemaVersion identifies the deliberately breaking report contract.
Variables ¶
This section is empty.
Functions ¶
func EvidenceID ¶
EvidenceID creates a stable identity from a provider-owned source and key.
func SemanticID ¶
SemanticID hashes length-delimited, versioned semantic inputs. Callers must exclude display text, timestamps and engine-temporary identities.
Types ¶
type AccessMethodChange ¶
AccessMethodChange compares modeled access methods, not runtime behavior.
type AccessProperties ¶
type AccessProperties struct {
Method string `json:"method"`
UsedIndexes []string `json:"used_indexes"`
}
AccessProperties describes a model access, not native access_type.
type Action ¶
type Action struct {
Type ActionType `json:"type"`
SQL string `json:"sql,omitempty"`
Explanation string `json:"explanation,omitempty"`
// ExplanationRef identifies the message template that produced Explanation.
ExplanationRef *MessageRef `json:"explanation_ref,omitempty"`
}
Action is emitted only when an engine can render a safe action.
type ActionDefinition ¶
type ActionDefinition struct {
ID string `json:"id"`
// Kind selects the populated payload member.
// One of: INDEX, REWRITE, OPERATIONAL.
Kind string `json:"kind"`
Target SQLTarget `json:"target"`
Index *IndexDefinition `json:"index,omitempty"`
Rewrite *RewriteDefinition `json:"rewrite,omitempty"`
Operational *Message `json:"operational,omitempty"`
}
ActionDefinition is a typed, non-executable design. SQL is not a payload.
type ActionExecution ¶
type ActionExecution struct {
// Availability describes whether Analyze can return SQL. Analyze never applies it.
// One of: AVAILABLE, ADVISORY_ONLY, NOT_REQUESTED, UNAVAILABLE.
Availability string `json:"availability"`
SQL string `json:"sql,omitempty"`
}
ActionExecution describes availability only; Analyze never applies SQL.
type ActionPayload ¶
type ActionPayload struct {
Index *IndexDefinition `json:"index,omitempty"`
Rewrite *RewriteDefinition `json:"rewrite,omitempty"`
Operational *Message `json:"operational,omitempty"`
}
ActionPayload is a controlled union with exactly one matching member.
type ActionPrecondition ¶
ActionPrecondition is an outstanding review requirement, not a passed check.
type ActionType ¶
type ActionType string
ActionType identifies an executable or operational recommendation.
const ( // ActionSQL contains executable SQL rendered from a structured design. ActionSQL ActionType = "SQL" // ActionOperational contains a non-SQL operational step. ActionOperational ActionType = "OPERATIONAL" )
type Agent ¶
type Agent interface {
Engine() Engine
ServerVersion() ServerVersion
VersionProfile() VersionProfile
Capabilities() []CapabilityStatus
Explain(context.Context, string, ...RequestOption) (*ExplainResult, error)
Analyze(context.Context, string, ...RequestOption) (*AnalyzeResult, error)
AnalyzeStatic(context.Context, string, ...RequestOption) (*AnalyzeResult, error)
InvalidateTableInfoCache(schemaName, tableName string)
InvalidateTableCacheAll(schemaName, tableName string)
Close()
}
Agent is the common lifecycle and analysis contract implemented by a database-specific engine.
type AnalysisContext ¶
type AnalysisContext struct {
SQL string `json:"sql"`
Engine Engine `json:"engine"`
EngineVersion string `json:"engine_version,omitempty"`
Database string `json:"database,omitempty"`
// DefaultSchema is an explicit static name-resolution assumption, not catalog evidence.
DefaultSchema string `json:"default_schema,omitempty"`
Profile VersionProfile `json:"profile"`
Capabilities []CapabilityStatus `json:"capabilities"`
Language string `json:"language"`
Mode string `json:"mode"`
Identity string `json:"identity"`
Recording RecordingReport `json:"recording"`
}
AnalysisContext describes the immutable inputs and effective output level.
func NewReportContext ¶
func NewReportContext(context AnalysisContext, mode string) AnalysisContext
NewReportContext creates a deterministic report context for one provider request. The identity is derived from the complete validated request input.
type AnalysisError ¶
type AnalysisError struct {
Code ErrorCode `json:"code"`
Engine Engine `json:"engine,omitempty"`
Stage AnalysisStage `json:"stage,omitempty"`
Capability CapabilityID `json:"capability,omitempty"`
Message string `json:"message,omitempty"`
Cause error `json:"-"`
}
AnalysisError is a structured execution error. A usable partial result may accompany it. Cause is available through errors.Is/errors.As but is excluded from JSON to avoid leaking driver data.
func (*AnalysisError) Error ¶
func (e *AnalysisError) Error() string
Error returns localized text when supplied and otherwise a stable structural description.
func (*AnalysisError) Unwrap ¶
func (e *AnalysisError) Unwrap() error
Unwrap exposes the underlying operational cause without serializing it.
type AnalysisStage ¶
type AnalysisStage string
AnalysisStage identifies the stage that produced an error or diagnostic.
const ( // StageProfile identifies version/profile selection. StageProfile AnalysisStage = "PROFILE" // StageParse identifies parsing and PostgreSQL AST conversion. StageParse AnalysisStage = "PARSE" // StageBind identifies name binding. StageBind AnalysisStage = "BIND" // StageMetadata identifies catalog and statistics collection. StageMetadata AnalysisStage = "METADATA" // StageExplain identifies native EXPLAIN execution or decoding. StageExplain AnalysisStage = "EXPLAIN" // StageRule identifies static or dynamic rule analysis. StageRule AnalysisStage = "RULE" // StageCost identifies cost and what-if evaluation. StageCost AnalysisStage = "COST" // StageProvider identifies cost-provider selection or operation. StageProvider AnalysisStage = "PROVIDER" )
type AnalysisStatus ¶
type AnalysisStatus string
AnalysisStatus is the completeness of a non-fatal result.
const ( // AnalysisStatusComplete means all requested supported stages completed. AnalysisStatusComplete AnalysisStatus = "COMPLETE" // AnalysisStatusPartial means a result is reliable but has limitations. AnalysisStatusPartial AnalysisStatus = "PARTIAL" // AnalysisStatusUnsupported means no requested conclusion can be produced. AnalysisStatusUnsupported AnalysisStatus = "UNSUPPORTED" )
type AnalysisSummary ¶
type AnalysisSummary struct {
Status AnalysisStatus `json:"status"`
IssueCount int `json:"issue_count"`
RecommendationCount int `json:"recommendation_count"`
CandidateDispositions []DispositionCount `json:"candidate_dispositions"`
Conclusion Message `json:"conclusion"`
}
AnalysisSummary counts observed facts, independently of detail truncation.
type AnalyzeResult ¶
type AnalyzeResult struct {
// Execution records this invocation; absent on legacy producers.
Execution *ExecutionReport `json:"execution,omitempty"`
// Explain is independently usable evidence collected in the same invocation.
Explain *ExplainResult `json:"explain,omitempty"`
// SchemaVersion is the value of ReportSchemaVersion for this report.
SchemaVersion string `json:"schema_version"`
Context AnalysisContext `json:"context"`
Summary AnalysisSummary `json:"summary"`
Issues []*Issue `json:"issues"`
Recommendations []Recommendation `json:"recommendations"`
Tables []TableSnapshot `json:"tables"`
Assessment AssessmentReport `json:"assessment"`
Diagnostics *DiagnosticReport `json:"diagnostics,omitempty"`
DebugTrace *DebugTraceReport `json:"debug_trace,omitempty"`
// Language is a migration-only adapter field. It does not authorize
// flattening the public report's Context and message contracts.
Language string `json:"-"`
}
AnalyzeResult is the versioned user-facing report, also referenced by SQL engine adapters as Report.
func (*AnalyzeResult) ValidateResult ¶
func (r *AnalyzeResult) ValidateResult() error
ValidateResult distinguishes execution-only failures from usable reports. Explain is independent and may be omitted by a consumer's documented projection.
type AssessmentReport ¶
type AssessmentReport struct {
Coverage CoverageReport `json:"coverage"`
NativePlan *NativePlanReport `json:"native_plan,omitempty"`
Candidates []CandidateReport `json:"candidates"`
Evaluations []EvaluationReport `json:"evaluations"`
Evidence []EvidenceRecord `json:"evidence"`
Limitations []Notice `json:"limitations"`
NextActions []NextAction `json:"next_actions"`
}
AssessmentReport retains business evidence with debug recording disabled.
type BenefitAssessment ¶
type BenefitAssessment struct {
EvaluationID string `json:"evaluation_id"`
// Basis identifies the cost space of the copied comparison.
// One of: INTERNAL_MODEL, NATIVE_PLANNER.
Basis string `json:"basis"`
Scope BenefitScope `json:"scope"`
ActionIDs []string `json:"action_ids"`
// Attribution is exact for the applied action set, never an individual member gain.
// One of: EXACT_ACTION_SET.
Attribution string `json:"attribution"`
Metrics []MetricComparison `json:"metrics"`
PlanChanges []PlanChange `json:"plan_changes"`
}
BenefitAssessment attributes a comparison only to its exact applied action set.
type BenefitScope ¶
type BenefitScope struct {
// Kind identifies the full query or a proven local occurrence or operator.
// One of: WHOLE_QUERY, RELATION_ACCESS, OPERATOR.
Kind string `json:"kind"`
Target *SQLTarget `json:"target,omitempty"`
BaselineNodeID string `json:"baseline_node_id,omitempty"`
CandidateNodeID string `json:"candidate_node_id,omitempty"`
MatchBasis string `json:"match_basis,omitempty"`
}
BenefitScope identifies the full query or a proven local occurrence/node pair.
type CandidateCost ¶
type CandidateCost struct {
ID string `json:"id"`
Design string `json:"design"`
Estimate *CostEstimate `json:"estimate,omitempty"`
// CostRatio and CostReductionPercent are the legacy model comparison
// fields. New reports expose the explicitly scoped pointers below.
CostRatio float64 `json:"cost_ratio,omitempty"`
CostReductionPercent float64 `json:"cost_reduction_percent,omitempty"`
ModelCostRatio *float64 `json:"model_cost_ratio,omitempty"`
ModelCostReductionPercent *float64 `json:"model_cost_reduction_percent,omitempty"`
Interpretation CostInterpretation `json:"interpretation,omitempty"`
Limitations []CostLimitationCode `json:"limitations,omitempty"`
Status WhatIfStatus `json:"status"`
Reason string `json:"reason,omitempty"`
SuggestionIDs []string `json:"suggestion_ids,omitempty"`
// UsedHypotheticalIndexes lists the submitted design names observed in native EXPLAIN.
UsedHypotheticalIndexes []string `json:"used_hypothetical_indexes,omitempty"`
// UsedHypotheticalSuggestionIDs identifies only the designs used by the native plan.
UsedHypotheticalSuggestionIDs []string `json:"used_hypothetical_suggestion_ids,omitempty"`
// CreatedHypotheticalSuggestionIDs records successful submissions before an attempt failed.
CreatedHypotheticalSuggestionIDs []string `json:"-"`
// NativeAccesses supplies per-node evidence to the connected report projector.
NativeAccesses []RecordedNativeAccess `json:"-"`
}
CandidateCost summarizes one structured candidate design and its cost.
type CandidateReport ¶
type CandidateReport struct {
// GenerationReasons are producer-recorded mechanisms, never adoption decisions.
GenerationReasons []RationaleClaim `json:"generation_reasons"`
ID string `json:"id"`
Kind string `json:"kind"`
IssueIDs []string `json:"issue_ids"`
FindingIDs []string `json:"finding_ids"`
Rule string `json:"rule"`
Targets []SQLTarget `json:"targets"`
Actions []ActionDefinition `json:"actions"`
Evidence []EvidenceRef `json:"evidence"`
Disposition string `json:"disposition"`
FinalDecision DecisionRecord `json:"final_decision"`
EvaluationIDs []string `json:"evaluation_ids"`
MergedInto string `json:"merged_into,omitempty"`
SupersededBy string `json:"superseded_by,omitempty"`
}
CandidateReport is a generated, non-executable action and its final decision.
type CapabilityID ¶
type CapabilityID string
CapabilityID identifies an independently reportable engine capability.
const ( // CapabilityParser identifies SQL parser support. CapabilityParser CapabilityID = "PARSER" // CapabilityJSONExplain identifies safe JSON EXPLAIN support. CapabilityJSONExplain CapabilityID = "JSON_EXPLAIN" // CapabilityParameterizedSQL identifies parameter-reference support. CapabilityParameterizedSQL CapabilityID = "PARAMETERIZED_SQL" // CapabilityMetadata identifies catalog metadata support. CapabilityMetadata CapabilityID = "METADATA" // CapabilityStatistics identifies ordinary statistics support. CapabilityStatistics CapabilityID = "STATISTICS" // CapabilityExtendedStatistics identifies multivariate statistics support. CapabilityExtendedStatistics CapabilityID = "EXTENDED_STATISTICS" // CapabilityStaticRules identifies AST-only rules. CapabilityStaticRules CapabilityID = "STATIC_RULES" // CapabilityDynamicRules identifies metadata/plan-dependent rules. CapabilityDynamicRules CapabilityID = "DYNAMIC_RULES" // CapabilityIndexSuggestion identifies executable index recommendations. CapabilityIndexSuggestion CapabilityID = "INDEX_SUGGESTION" // CapabilityInternalCost identifies an engine's internal cost provider. CapabilityInternalCost CapabilityID = "INTERNAL_COST" // CapabilityHypoPG identifies the optional HypoPG provider. CapabilityHypoPG CapabilityID = "HYPOPG" // CapabilitySamples identifies explicitly enabled sampling. CapabilitySamples CapabilityID = "SAMPLES" )
type CapabilityStatus ¶
type CapabilityStatus struct {
ID CapabilityID `json:"id"`
Status CapabilitySupport `json:"status"`
Reason string `json:"reason,omitempty"`
}
CapabilityStatus reports the effective state after profile, build, runtime, and configuration constraints are combined.
type CapabilitySupport ¶
type CapabilitySupport string
CapabilitySupport describes whether a capability can be used reliably.
const ( // CapabilitySupported means the capability is available as documented. CapabilitySupported CapabilitySupport = "SUPPORTED" // CapabilityDegraded means the capability is available with limitations. CapabilityDegraded CapabilitySupport = "DEGRADED" CapabilityUnavailable CapabilitySupport = "UNAVAILABLE" )
type CheckRecord ¶
type CheckRecord struct {
ID string `json:"id"`
Stage string `json:"stage"`
Status string `json:"status"`
Outcome string `json:"outcome,omitempty"`
ReasonCode string `json:"reason_code,omitempty"`
}
CheckRecord distinguishes skipped checks from executed checks with no finding.
type CollectionCount ¶
type CollectionCount struct {
Scope string `json:"scope"`
Observed int `json:"observed"`
Returned int `json:"returned"`
Omitted int `json:"omitted"`
}
CollectionCount counts observed, returned and omitted objects.
type ColumnDefinition ¶
type ColumnDefinition struct {
Name string `json:"name"`
Position int `json:"position"`
Type string `json:"type"`
Nullable *bool `json:"nullable"`
Charset string `json:"charset,omitempty"`
Collation string `json:"collation,omitempty"`
Generated *bool `json:"generated"`
Identity *bool `json:"identity"`
}
ColumnDefinition distinguishes unknown properties from known false values.
type ColumnStatistics ¶
type ColumnStatistics struct {
Name string `json:"name"`
EstimatedDistinctValues Metric[float64] `json:"estimated_distinct_values"`
DistinctRatio Metric[float64] `json:"distinct_ratio"`
NullFraction Metric[float64] `json:"null_fraction"`
AverageWidthBytes Metric[float64] `json:"average_width_bytes"`
HistogramStatus string `json:"histogram_status"`
}
ColumnStatistics exposes estimates and availability, not business values.
type Confidence ¶
type Confidence string
Confidence is a qualitative estimate of model coverage.
const ( // ConfidenceHigh indicates complete modeled inputs for a supported shape. ConfidenceHigh Confidence = "HIGH" // ConfidenceMedium indicates conservative simplifications. ConfidenceMedium Confidence = "MEDIUM" // ConfidenceLow indicates material missing inputs or alignment differences. ConfidenceLow Confidence = "LOW" )
type ConstraintDefinition ¶
type ConstraintDefinition struct {
Name string `json:"name"`
Kind string `json:"kind"`
Columns []string `json:"columns"`
}
ConstraintDefinition is emitted only from collected constraint evidence.
type CostEstimate ¶
type CostEstimate struct {
Cost float64 `json:"cost"`
OutputRows float64 `json:"output_rows,omitempty"`
Confidence Confidence `json:"confidence"`
Reason string `json:"reason,omitempty"`
}
CostEstimate is one full-query estimate in a declared provider identity.
type CostInterpretation ¶
type CostInterpretation string
CostInterpretation defines the only valid interpretation of a relative cost comparison. It prevents clients from treating model ratios as native planner costs or measured runtime.
const ( // CostInterpretationRelativeLogicalIRModelOnly means the values compare two // alternatives only inside one identical Logical IR model and evidence snapshot. CostInterpretationRelativeLogicalIRModelOnly CostInterpretation = "RELATIVE_LOGICAL_IR_MODEL_ONLY" // CostInterpretationRelativeInternalModelOnly means the values compare two // alternatives only inside one identical sql-gunyu internal model. CostInterpretationRelativeInternalModelOnly CostInterpretation = "RELATIVE_INTERNAL_MODEL_ONLY" // CostInterpretationRelativeNativePlannerCostOnly means the values compare // native planner estimates in one identical planning context. They are not // measured execution time. CostInterpretationRelativeNativePlannerCostOnly CostInterpretation = "RELATIVE_NATIVE_PLANNER_COST_ONLY" )
type CostLimitationCode ¶
type CostLimitationCode string
CostLimitationCode is a stable machine-readable boundary on cost results.
const ( // CostLimitationNotMySQLNativeCost means the values are not MySQL query_cost. CostLimitationNotMySQLNativeCost CostLimitationCode = "not_mysql_native_cost" // CostLimitationNotPostgreSQLNativeCost applies to modeled PostgreSQL costs. CostLimitationNotPostgreSQLNativeCost CostLimitationCode = "not_postgresql_native_cost" // CostLimitationNotDatabasePlanPrediction means the result does not predict // which physical plan the database will select. CostLimitationNotDatabasePlanPrediction CostLimitationCode = "not_database_plan_prediction" // CostLimitationNotRuntimePrediction means the result does not predict latency. CostLimitationNotRuntimePrediction CostLimitationCode = "not_runtime_prediction" // CostLimitationHypotheticalIndexOnly means the planner evaluated a // hypothetical index rather than a physically created index. CostLimitationHypotheticalIndexOnly CostLimitationCode = "hypothetical_index_only" // CostLimitationNotPhysicalIndexValidation means the result does not prove // how a physically built index behaves under execution. CostLimitationNotPhysicalIndexValidation CostLimitationCode = "not_physical_index_validation" // CostLimitationNoPartitionPruningCost means partition selection and pruning // are outside the current Logical IR cost comparison. CostLimitationNoPartitionPruningCost CostLimitationCode = "no_partition_pruning_cost" // CostLimitationNoIndexMergeCost means native index-merge access is outside // the current Logical IR physical access model. CostLimitationNoIndexMergeCost CostLimitationCode = "no_index_merge_cost" // CostLimitationNoJoinOrderSearch means the comparison costs the bound join // tree but does not enumerate alternative join orders. CostLimitationNoJoinOrderSearch CostLimitationCode = "no_join_order_search" // CostLimitationNoDMLMaintenanceCost means write amplification, index // maintenance, locking, and logging costs are not modeled for DML. CostLimitationNoDMLMaintenanceCost CostLimitationCode = "no_dml_maintenance_cost" // CostLimitationPartialPartitionPruningCost means only explicit partition // selection backed by per-partition row evidence is modeled. CostLimitationPartialPartitionPruningCost CostLimitationCode = "partial_partition_pruning_cost" // CostLimitationPartialIndexMergeCost means only AND intersections of // independently useful indexes are modeled. CostLimitationPartialIndexMergeCost CostLimitationCode = "partial_index_merge_cost" // CostLimitationBoundedJoinOrderSearch means deterministic inner-join // reordering is searched while outer joins and Apply remain barriers. CostLimitationBoundedJoinOrderSearch CostLimitationCode = "bounded_join_order_search" // CostLimitationPartialDMLMaintenanceCost means the model includes row and // index maintenance work but not locking, logging, triggers, or cascades. CostLimitationPartialDMLMaintenanceCost CostLimitationCode = "partial_dml_maintenance_cost" )
func LogicalIRCostLimitations ¶
func LogicalIRCostLimitations() []CostLimitationCode
LogicalIRCostLimitations returns the stable boundaries required on every Logical IR model comparison. A new slice is returned for safe caller mutation.
func PostgreSQLInternalCostLimitations ¶
func PostgreSQLInternalCostLimitations() []CostLimitationCode
PostgreSQLInternalCostLimitations returns limitations for historical PostgreSQL internal model results.
func PostgreSQLNativeHypoPGLimitations ¶
func PostgreSQLNativeHypoPGLimitations() []CostLimitationCode
PostgreSQLNativeHypoPGLimitations returns the stable boundaries required on every PostgreSQL native/HypoPG comparison.
type CostModelIdentity ¶
type CostModelIdentity struct {
Engine Engine `json:"engine"`
Provider CostProvider `json:"provider"`
Profile string `json:"profile,omitempty"`
ServerVersion string `json:"server_version,omitempty"`
Revision string `json:"revision,omitempty"`
ExtensionVersion string `json:"extension_version,omitempty"`
DatabaseOID uint32 `json:"database_oid,omitempty"`
EffectiveRoleOID uint32 `json:"effective_role_oid,omitempty"`
SearchPathDigest string `json:"search_path_digest,omitempty"`
RLSContextDigest string `json:"rls_context_digest,omitempty"`
PlannerSettingsDigest string `json:"planner_settings_digest,omitempty"`
CatalogStatisticsDigest string `json:"catalog_statistics_digest,omitempty"`
Unit string `json:"unit"`
}
CostModelIdentity defines the context in which costs are comparable.
type CostProvider ¶
type CostProvider string
CostProvider identifies a cost space. Values from different providers must never be compared arithmetically.
const ( // CostProviderMySQLInternal is sql-gunyu's MySQL model. CostProviderMySQLInternal CostProvider = "SQL_GUNYU_MYSQL_INTERNAL" // CostProviderPostgreSQLInternal identifies historical PostgreSQL internal model results. CostProviderPostgreSQLInternal CostProvider = "SQL_GUNYU_POSTGRESQL_INTERNAL" // CostProviderPostgreSQLNativeHypoPG is PostgreSQL native/HypoPG cost. CostProviderPostgreSQLNativeHypoPG CostProvider = "POSTGRESQL_NATIVE_HYPOPG" )
type CoverageReport ¶
type CoverageReport struct {
Status AnalysisStatus `json:"status"`
Scope []string `json:"scope"`
PolicyIdentity string `json:"policy_identity"`
Stages []CheckRecord `json:"stages"`
Checks []CheckRecord `json:"checks"`
Gaps []Notice `json:"gaps"`
}
CoverageReport reports observed execution, not inferred rule selection.
type DebugEvent ¶
type DebugEvent struct {
ID string `json:"id"`
Stage string `json:"stage"`
Subject SubjectRef `json:"subject"`
EventCode string `json:"event_code"`
}
DebugEvent contains a controlled event code and typed subject.
type DebugTraceReport ¶
type DebugTraceReport struct {
SchemaVersion string `json:"schema_version"`
Status AnalysisStatus `json:"status"`
Events []DebugEvent `json:"events"`
SearchSummary ObservationCount `json:"search_summary"`
CacheDiagnostics ObservationCount `json:"cache_diagnostics"`
Omissions []Omission `json:"omissions"`
}
DebugTraceReport is request scoped. Unobserved counters are never zero-filled.
type DecisionRecord ¶
type DecisionRecord struct {
ID string `json:"id"`
Stage string `json:"stage"`
Subject SubjectRef `json:"subject"`
Outcome string `json:"outcome"`
ReasonCode string `json:"reason_code"`
Message Message `json:"message"`
Evidence []EvidenceRef `json:"evidence"`
EvaluationID string `json:"evaluation_id,omitempty"`
}
DecisionRecord is one observed decision about one controlled subject.
type Diagnostic ¶
type Diagnostic struct {
Code DiagnosticCode `json:"code"`
Stage AnalysisStage `json:"stage"`
Feature string `json:"feature,omitempty"`
Message string `json:"message,omitempty"`
}
Diagnostic is a stable machine-readable warning or unsupported feature.
type DiagnosticCode ¶
type DiagnosticCode string
DiagnosticCode identifies a non-fatal limitation or warning.
const ( // DiagnosticCostEstimateOnly distinguishes estimates from execution time. DiagnosticCostEstimateOnly DiagnosticCode = "COST_ESTIMATE_ONLY" // DiagnosticNotEvaluableStats indicates insufficient reliable statistics. DiagnosticNotEvaluableStats DiagnosticCode = "NOT_EVALUABLE_STATS" // DiagnosticNotEvaluablePlan indicates an unsupported plan shape. DiagnosticNotEvaluablePlan DiagnosticCode = "NOT_EVALUABLE_PLAN" // DiagnosticNotEvaluableOverflow indicates unsafe non-finite cost arithmetic. DiagnosticNotEvaluableOverflow DiagnosticCode = "NOT_EVALUABLE_OVERFLOW" // DiagnosticUnknownASTNode indicates an unsupported local AST node. DiagnosticUnknownASTNode DiagnosticCode = "UNKNOWN_AST_NODE" // DiagnosticUnknownPlanNode indicates an unknown native plan node. DiagnosticUnknownPlanNode DiagnosticCode = "UNKNOWN_PLAN_NODE" // DiagnosticPlanningContextMismatch indicates non-comparable contexts. DiagnosticPlanningContextMismatch DiagnosticCode = "PLANNING_CONTEXT_MISMATCH" // DiagnosticProviderFallback records an all-or-nothing provider fallback. DiagnosticProviderFallback DiagnosticCode = "PROVIDER_FALLBACK" DiagnosticHypoPGUnavailable DiagnosticCode = "HYPOPG_UNAVAILABLE" // DiagnosticHypoPGScenarioFailed means at least one native scenario failed. DiagnosticHypoPGScenarioFailed DiagnosticCode = "HYPOPG_SCENARIO_FAILED" // DiagnosticHypoPGCleanupFailed means the native results and session were discarded. DiagnosticHypoPGCleanupFailed DiagnosticCode = "HYPOPG_CLEANUP_FAILED" // DiagnosticSearchIncomplete means a configured search budget left alternatives untested. DiagnosticSearchIncomplete DiagnosticCode = "SEARCH_INCOMPLETE" // DiagnosticUnsafeRecommendation indicates that SQL action was withheld. DiagnosticUnsafeRecommendation DiagnosticCode = "UNSAFE_RECOMMENDATION" // for the requested analysis while nonfatal AST evidence was retained. DiagnosticMetadataUnavailable DiagnosticCode = "METADATA_UNAVAILABLE" // DiagnosticStatisticsMissing indicates that planner statistics required by // the analysis have not been collected. DiagnosticStatisticsMissing DiagnosticCode = "STATISTICS_MISSING" // DiagnosticStatisticsTargetDisabled indicates that statistics collection // is disabled for an applicable column. DiagnosticStatisticsTargetDisabled DiagnosticCode = "STATISTICS_TARGET_DISABLED" // DiagnosticStatisticsStale indicates that PostgreSQL's configured // auto-analyze threshold has been reached. DiagnosticStatisticsStale DiagnosticCode = "STATISTICS_STALE" // DiagnosticPartitionStatisticsStale indicates that parent statistics may // not include newer child or partition changes. DiagnosticPartitionStatisticsStale DiagnosticCode = "PARTITION_STATISTICS_STALE" // DiagnosticExtendedStatisticsMissing indicates that correlation between // multiple predicate columns is unknown because no applicable persistent // statistics object exists. DiagnosticExtendedStatisticsMissing DiagnosticCode = "EXTENDED_STATISTICS_MISSING" )
type DiagnosticPolicy ¶
type DiagnosticPolicy struct {
Thresholds DiagnosticThresholds `json:"thresholds"`
Severity SeverityPolicy `json:"severity"`
}
DiagnosticPolicy is the immutable, Agent-scoped diagnostic configuration. It is copied into an Agent and applies to every request handled by that Agent.
func DefaultDiagnosticPolicy ¶
func DefaultDiagnosticPolicy() DiagnosticPolicy
DefaultDiagnosticPolicy returns a fresh policy with the cross-database defaults. The returned map is never shared with another policy.
func (DiagnosticPolicy) Clone ¶
func (policy DiagnosticPolicy) Clone() DiagnosticPolicy
Clone returns a defensive deep copy of the policy.
func (DiagnosticPolicy) Resolve ¶
func (policy DiagnosticPolicy) Resolve() (DiagnosticPolicy, error)
Resolve validates the policy, fills zero thresholds from the defaults, and returns a defensive deep copy suitable for freezing inside an Agent.
func (DiagnosticPolicy) Validate ¶
func (policy DiagnosticPolicy) Validate() error
Validate checks explicitly configured values. Zero thresholds are allowed as unspecified values and are filled by Resolve. Negative thresholds, empty override keys, and severities outside the public 0..4 range are rejected.
type DiagnosticReport ¶
type DiagnosticReport struct {
Status AnalysisStatus `json:"status"`
Decisions []DecisionRecord `json:"decisions"`
Findings []EvidenceRecord `json:"findings"`
RewriteAttempts []RewriteAttemptDiagnostic `json:"rewrite_attempts"`
Omissions []Omission `json:"omissions"`
}
DiagnosticReport contains observed nonfinal decisions and coordinated findings.
type DiagnosticThresholds ¶
type DiagnosticThresholds struct {
LargeTableRows int64 `json:"large_table_rows"`
LargeScanRows int64 `json:"large_scan_rows"`
LargeSortRows int64 `json:"large_sort_rows"`
}
DiagnosticThresholds defines Agent-scoped row-count boundaries used by evidence-based diagnostics. Each threshold is an inclusive lower bound. A zero value is resolved from DefaultDiagnosticPolicy during Agent creation.
type DispositionCount ¶
DispositionCount counts all observed candidates of one final disposition.
type ErrorCode ¶
type ErrorCode string
ErrorCode identifies an analysis execution failure independently of localized wording.
const ( // ErrParseError indicates invalid SQL or a rejected multi-statement input. ErrParseError ErrorCode = "PARSE_ERROR" // ErrUnsupportedParameterizedSQL indicates that the SQL contains ParamRef. ErrUnsupportedParameterizedSQL ErrorCode = "UNSUPPORTED_PARAMETERIZED_SQL" // ErrUnsupportedServerVersion indicates an unsupported connected server. ErrUnsupportedServerVersion ErrorCode = "UNSUPPORTED_SERVER_VERSION" // ErrUnsupportedSQLShape indicates an unsupported root statement shape. ErrUnsupportedSQLShape ErrorCode = "UNSUPPORTED_SQL_SHAPE" // ErrExplain indicates that safe native EXPLAIN failed. ErrExplain ErrorCode = "EXPLAIN_ERROR" // ErrPlanningContextMismatch indicates incompatible metadata/plan contexts. ErrPlanningContextMismatch ErrorCode = "PLANNING_CONTEXT_MISMATCH" ErrProviderUnavailable ErrorCode = "PROVIDER_UNAVAILABLE" // ErrInsufficientPrivileges indicates that required catalog/statistics data // is intentionally hidden from the effective PostgreSQL role. ErrInsufficientPrivileges ErrorCode = "INSUFFICIENT_PRIVILEGES" )
type EstimatedAccess ¶
type EstimatedAccess struct {
ID string `json:"id"`
Target SQLTarget `json:"target"`
Method string `json:"method"`
UsedIndexes []string `json:"used_indexes"`
OutputRows *float64 `json:"output_rows"`
RowsExamined *float64 `json:"rows_examined"`
RowScope string `json:"row_scope"`
}
EstimatedAccess preserves every recorded relation occurrence, not a first leaf.
type EstimatedPlan ¶
type EstimatedPlan struct {
ID string `json:"id"`
Fingerprint string `json:"fingerprint"`
Origin string `json:"origin"`
Summary PlanSummary `json:"summary"`
Accesses []EstimatedAccess `json:"accesses"`
StructureStatus string `json:"structure_status"`
Root *EstimatedPlanNode `json:"root,omitempty"`
Limitations []Notice `json:"limitations"`
}
EstimatedPlan is a controlled projection of an actually estimated plan.
type EstimatedPlanInput ¶
type EstimatedPlanInput struct {
Role string `json:"role"`
Node *EstimatedPlanNode `json:"node"`
}
EstimatedPlanInput assigns explicit roles to children.
type EstimatedPlanNode ¶
type EstimatedPlanNode struct {
ID string `json:"id"`
Operator string `json:"operator"`
Target *SQLTarget `json:"target,omitempty"`
Estimates NodeEstimates `json:"estimates"`
Access *AccessProperties `json:"access,omitempty"`
Join *JoinProperties `json:"join,omitempty"`
PredicateRefs []EvidenceRef `json:"predicate_refs"`
Inputs []EstimatedPlanInput `json:"inputs"`
Limitations []Notice `json:"limitations"`
}
EstimatedPlanNode is recorded at physical operator construction time.
type EvaluationAlternative ¶
type EvaluationAlternative struct {
Status string `json:"status"`
Context EvaluationContext `json:"context"`
Plan *EstimatedPlan `json:"plan,omitempty"`
UsedIndexes []string `json:"used_indexes"`
// UsedActionIDs links adopted hypothetical indexes to submitted scenario actions.
UsedActionIDs []string `json:"used_action_ids,omitempty"`
// NativeAccesses records the observed access nodes of this alternative.
NativeAccesses []NativeAccess `json:"native_accesses,omitempty"`
Limitations []Notice `json:"limitations"`
}
EvaluationAlternative owns its plan and comparability evidence.
type EvaluationComparison ¶
type EvaluationComparison struct {
Metrics []MetricComparison `json:"metrics"`
PlanChanges []PlanChange `json:"plan_changes"`
Status string `json:"status"`
Cost *RelativeModelCost `json:"cost,omitempty"`
PlanChanged *bool `json:"plan_changed"`
NodeMatches []NodeMatch `json:"node_matches"`
StructureStatus string `json:"structure_status"`
Summary Message `json:"summary"`
}
EvaluationComparison is derived from the engine's existing comparator.
type EvaluationContext ¶
type EvaluationContext struct {
Provider CostProvider `json:"provider"`
ModelIdentity CostModelIdentity `json:"model_identity"`
Scope CostScope `json:"scope"`
AnalysisIdentity string `json:"analysis_identity"`
LogicalQueryFingerprint string `json:"logical_query_fingerprint"`
CatalogIdentity string `json:"catalog_identity"`
StatisticsIdentity string `json:"statistics_identity"`
ConstraintIdentity string `json:"constraint_identity,omitempty"`
}
EvaluationContext records each side's cost space and evidence identities.
type EvaluationReport ¶
type EvaluationReport struct {
ID string `json:"id"`
Kind string `json:"kind"`
Status string `json:"status"`
Title Message `json:"title"`
Scenario EvaluationScenario `json:"scenario"`
Baseline *EvaluationAlternative `json:"baseline,omitempty"`
Candidate *EvaluationAlternative `json:"candidate,omitempty"`
Comparison *EvaluationComparison `json:"comparison,omitempty"`
Decision DecisionRecord `json:"decision"`
Limitations []Notice `json:"limitations"`
}
EvaluationReport describes one actually attempted optimization scenario.
func (EvaluationReport) Comparable ¶
func (e EvaluationReport) Comparable() bool
Comparable checks paired cost-space and evidence identities without estimating costs.
type EvaluationScenario ¶
type EvaluationScenario struct {
Scope CostScope `json:"scope"`
CandidateIDs []string `json:"candidate_ids"`
ActionIDs []string `json:"action_ids"`
Changes []ScenarioChange `json:"changes"`
SearchMode string `json:"search_mode"`
IndependentEvaluation bool `json:"independent_evaluation"`
RewriteAttemptID string `json:"rewrite_attempt_id,omitempty"`
}
EvaluationScenario describes applied mutations, not independent member gains.
type EvidenceRecord ¶
type EvidenceRecord struct {
ID string `json:"id"`
Kind string `json:"kind"`
Source string `json:"source"`
Target *SQLTarget `json:"target,omitempty"`
SnapshotIdentity string `json:"snapshot_identity,omitempty"`
Quality string `json:"quality"`
ClaimStrength string `json:"claim_strength"`
Dependencies []EvidenceRef `json:"dependencies"`
Policy *PolicyFact `json:"policy,omitempty"`
Finding *FindingFact `json:"finding,omitempty"`
Notice *Notice `json:"notice,omitempty"`
}
EvidenceRecord carries typed canonical facts not otherwise owned by an object.
type EvidenceRef ¶
EvidenceRef refers to an authoritative object, never an arbitrary JSONPath.
type ExecutionReport ¶
type ExecutionReport struct {
Status string `json:"status"`
ReportStatus string `json:"report_status"`
Stages []ExecutionStage `json:"stages"`
}
ExecutionReport is authoritative for stage execution. Absence on a historical report means unknown execution, not success. AVAILABLE does not authorize SQL.
func (*ExecutionReport) Validate ¶
func (e *ExecutionReport) Validate() error
Validate checks the six-stage execution contract, not report references.
type ExecutionStage ¶
type ExecutionStage struct {
ID string `json:"id"`
Status string `json:"status"`
ReasonCode string `json:"reason_code,omitempty"`
Message *Message `json:"message,omitempty"`
}
ExecutionStage records work performed, independently of diagnostic severity.
type ExplainFieldAnalysis ¶
type ExplainFieldAnalysis struct {
ToolTipRefs []MessageRef `json:"tool_tip_refs,omitempty"`
ToolTipSeparator *MessageRef `json:"tool_tip_separator,omitempty"`
ToolTip string `json:"tool_tip,omitempty"`
Results []ExplainFieldResult `json:"results,omitempty"`
}
ExplainFieldAnalysis contains localized diagnostics for a native plan field.
type ExplainFieldResult ¶
type ExplainFieldResult struct {
MessageRef *MessageRef `json:"message_ref,omitempty"`
Message string `json:"message"`
Severity Severity `json:"severity"`
}
ExplainFieldResult preserves the diagnostic severity emitted by the engine.
type ExplainResult ¶
type ExplainResult struct {
// Execution records the narrow native-plan request, when supplied by the engine.
Execution *ExecutionReport `json:"execution,omitempty"`
// Rows retains traditional native EXPLAIN fields without a physical binding claim.
Rows []NativeExplainRow `json:"rows,omitempty"`
SQL string `json:"sql"`
Engine Engine `json:"engine"`
EngineVersion string `json:"engine_version,omitempty"`
Database string `json:"database,omitempty"`
Profile VersionProfile `json:"profile"`
Capabilities []CapabilityStatus `json:"capabilities,omitempty"`
Status AnalysisStatus `json:"status"`
NativeExplain *NativeExplainSummary `json:"native_explain,omitempty"`
Warnings []Diagnostic `json:"warnings,omitempty"`
Unsupported []Diagnostic `json:"unsupported,omitempty"`
}
ExplainResult is the stable public summary returned by Agent.Explain.
func (*ExplainResult) Canonicalize ¶
func (result *ExplainResult) Canonicalize()
Canonicalize sorts and deduplicates result slices for stable JSON output.
func (*ExplainResult) Clone ¶
func (r *ExplainResult) Clone() *ExplainResult
Clone returns an isolated snapshot including row annotations and message args.
func (*ExplainResult) RenderMessages ¶
func (r *ExplainResult) RenderMessages(language string, render func(MessageRef, string) string)
RenderMessages localizes recorded references without running a query.
func (*ExplainResult) ValidateEvidence ¶
func (r *ExplainResult) ValidateEvidence() error
ValidateEvidence validates this sidecar independently of any analysis report. It rejects execution-only failures, while allowing empty native row sets when the engine explicitly returned a native summary (for example SELECT 1).
type FindingFact ¶
type FindingFact struct {
Rule string `json:"rule"`
Code string `json:"code"`
KeeperID string `json:"keeper_id,omitempty"`
Targets []SQLTarget `json:"targets"`
}
FindingFact retains a coordinated finding's identity and keeper reference.
type IndexDefinition ¶
type IndexDefinition struct {
ID string `json:"id"`
Name string `json:"name"`
Method string `json:"method"`
Unique *bool `json:"unique"`
Primary *bool `json:"primary"`
Visible *bool `json:"visible"`
Valid *bool `json:"valid"`
Keys []IndexKeyPart `json:"keys"`
Include []string `json:"include"`
PredicateStatus string `json:"predicate_status"`
MySQL *MySQLIndexProperties `json:"mysql,omitempty"`
PostgreSQL *PostgreSQLIndexProperties `json:"postgresql,omitempty"`
}
IndexDefinition is shared by existing and hypothetical designs.
type IndexKeyPart ¶
type IndexKeyPart struct {
Column string `json:"column,omitempty"`
ExpressionStatus string `json:"expression_status,omitempty"`
Direction string `json:"direction"`
PrefixLength *int64 `json:"prefix_length"`
PrefixUnit string `json:"prefix_unit,omitempty"`
NullOrdering string `json:"null_ordering,omitempty"`
OperatorClass string `json:"operator_class,omitempty"`
Collation string `json:"collation,omitempty"`
}
IndexKeyPart preserves order, prefix units and expression availability.
type IndexStatistics ¶
type IndexStatistics struct {
IndexID string `json:"index_id"`
PrefixCardinalities []Metric[float64] `json:"prefix_cardinalities"`
}
IndexStatistics describes observed prefix cardinalities.
type Issue ¶
type Issue struct {
ID string `json:"id"`
Code string `json:"code"`
Rule string `json:"rule"`
Source IssueSource `json:"source"`
Category string `json:"category"`
Severity Severity `json:"severity"`
Clause string `json:"clause,omitempty"`
Column string `json:"column,omitempty"`
Title Message `json:"title"`
Description Message `json:"description"`
// Message is the legacy rendered description used by engine rules that
// have not migrated to the structured Title and Description fields.
Message string `json:"message,omitempty"`
Targets []SQLTarget `json:"targets"`
Location *Location `json:"location,omitempty"`
Evidence []EvidenceRef `json:"evidence"`
Advice IssueAdvice `json:"advice"`
// Suggestions preserve engine-neutral guidance without promoting a
// non-executable action into a report recommendation.
Suggestions []*Suggestion `json:"suggestions"`
// Type and Schema preserve the flat identity consumed by legacy adapters.
// New consumers should use Code and Targets instead.
Type string `json:"type,omitempty"`
Schema string `json:"schema,omitempty"`
Table string `json:"table,omitempty"`
// DescriptionRef is read by engine-local re-rendering code. New reports
// persist the structured Title and Description instead.
DescriptionRef *MessageRef `json:"description_ref,omitempty"`
// LegacyDescription is the migration-only rendered source used to rebuild
// engine-specific suggestion and issue text without changing rule code.
LegacyDescription string `json:"-"`
}
Issue is a retained problem. Candidate rejection never removes its evidence.
type IssueAdvice ¶
type IssueAdvice struct {
Status string `json:"status"`
ReasonCode string `json:"reason_code,omitempty"`
Message *Message `json:"message,omitempty"`
}
IssueAdvice describes this report's advice, not a database remediation.
type IssueSource ¶
type IssueSource string
IssueSource identifies the evidence used to prove an issue.
const ( // IssueSourceAST means the issue is proven from SQL text and AST only. IssueSourceAST IssueSource = "AST" // IssueSourceMetadata means catalog metadata is required. IssueSourceMetadata IssueSource = "METADATA" // IssueSourceExplain means a native plan is required. IssueSourceExplain IssueSource = "EXPLAIN" // IssueSourceCombined means multiple evidence sources are required. IssueSourceCombined IssueSource = "COMBINED" )
type JoinProperties ¶
JoinProperties distinguishes the actual modeled algorithm and logical join.
type LegacyAnalyzeResult ¶
type LegacyAnalyzeResult struct {
SQL string `json:"sql"`
Engine Engine `json:"engine"`
EngineVersion string `json:"engine_version,omitempty"`
Language string `json:"language,omitempty"`
Database string `json:"database,omitempty"`
Profile VersionProfile `json:"profile"`
Capabilities []CapabilityStatus `json:"capabilities,omitempty"`
Status AnalysisStatus `json:"status"`
Issues []*Issue `json:"issues,omitempty"`
NativeExplain *NativeExplainSummary `json:"native_explain,omitempty"`
WhatIf *WhatIfEvaluation `json:"what_if,omitempty"`
TablesAnalyzed []RelationRef `json:"tables_analyzed,omitempty"`
Warnings []Diagnostic `json:"warnings,omitempty"`
Unsupported []Diagnostic `json:"unsupported,omitempty"`
}
LegacyAnalyzeResult is the prior flat engine result. New public callers use AnalyzeResult in report.go and receive an evidence-bound summary.
type LegacyOptimizeResult ¶
type LegacyOptimizeResult struct {
SQL string `json:"sql"`
Database string `json:"database,omitempty"`
Language string `json:"language,omitempty"`
Status AnalysisStatus `json:"status"`
Issues []*Issue `json:"issues,omitempty"`
NativeExplain *NativeExplainSummary `json:"native_explain,omitempty"`
WhatIf *WhatIfEvaluation `json:"what_if,omitempty"`
TablesAnalyzed []RelationRef `json:"tables_analyzed,omitempty"`
Warnings []Diagnostic `json:"warnings,omitempty"`
Unsupported []Diagnostic `json:"unsupported,omitempty"`
}
LegacyOptimizeResult is the prior internal MySQL optimizer dump retained for callers that have not migrated to the current public report.
type Location ¶
type Location struct {
StartOffset int `json:"start_offset"`
EndOffset int `json:"end_offset,omitempty"`
Line int `json:"line,omitempty"`
Column int `json:"column,omitempty"`
}
Location identifies a byte range and its one-based display coordinates. Byte offsets use the original UTF-8 SQL input.
type LogicalRewriteAttempt ¶
type LogicalRewriteAttempt struct {
AttemptID string `json:"attempt_id"`
Strategy string `json:"strategy"`
Selected bool `json:"selected,omitempty"`
Qualified bool `json:"qualified"`
NoSemanticChange bool `json:"no_semantic_change,omitempty"`
Executable bool `json:"executable"`
SQL string `json:"sql,omitempty"`
SafetyStatus string `json:"safety_status"`
QualificationReasons []string `json:"qualification_reasons,omitempty"`
DiffSummary LogicalRewriteDiff `json:"diff_summary"`
BaselineFingerprint string `json:"baseline_fingerprint"`
CandidateFingerprint string `json:"candidate_fingerprint"`
CostComparison *LogicalRewriteCostComparison `json:"cost_comparison,omitempty"`
EvidenceIdentities []string `json:"evidence_identities,omitempty"`
Limitations []string `json:"limitations,omitempty"`
}
LogicalRewriteAttempt describes one independently evaluated rewrite.
type LogicalRewriteCostComparison ¶
type LogicalRewriteCostComparison struct {
Provider CostProvider `json:"provider"`
ModelIdentity CostModelIdentity `json:"model_identity"`
Scope CostScope `json:"scope"`
AnalysisIdentity string `json:"analysis_identity"`
LogicalQueryFingerprint string `json:"logical_query_fingerprint"`
CatalogIdentity string `json:"catalog_identity"`
StatisticsIdentity string `json:"statistics_identity"`
Baseline CostEstimate `json:"baseline"`
Candidate CostEstimate `json:"candidate"`
Status WhatIfStatus `json:"status"`
ReasonCode string `json:"reason_code,omitempty"`
Reason string `json:"reason,omitempty"`
ModelCostRatio *float64 `json:"model_cost_ratio,omitempty"`
ModelCostReductionPercent *float64 `json:"model_cost_reduction_percent,omitempty"`
Interpretation CostInterpretation `json:"interpretation"`
Limitations []CostLimitationCode `json:"limitations"`
}
LogicalRewriteCostComparison is a comparable whole-query estimate in one declared model. It is neither a plan choice nor a runtime prediction.
type LogicalRewriteDiff ¶
type LogicalRewriteDiff struct {
AddedPredicates int `json:"added_predicates,omitempty"`
RemovedPredicates int `json:"removed_predicates,omitempty"`
MovedPredicates int `json:"moved_predicates,omitempty"`
CopiedPredicates int `json:"copied_predicates,omitempty"`
ResidualPredicates int `json:"residual_predicates,omitempty"`
ChangedRelations int `json:"changed_relations,omitempty"`
ChangedExpressions int `json:"changed_expressions,omitempty"`
}
LogicalRewriteDiff summarizes the semantic shape changed by one candidate.
type LogicalRewriteReport ¶
type LogicalRewriteReport struct {
QueryFingerprint string `json:"query_fingerprint"`
SelectedAttemptID string `json:"selected_attempt_id,omitempty"`
Attempts []LogicalRewriteAttempt `json:"attempts"`
}
LogicalRewriteReport exposes rewrite candidates without runtime claims.
type Message ¶
type Message struct {
Text string `json:"text"`
Ref MessageRef `json:"ref"`
}
Message preserves both rendered text and a persistable template reference.
func PlainMessage ¶
PlainMessage returns a rendered message without a template reference.
func RefsMessage ¶
func RefsMessage(text string, ref MessageRef) Message
RefsMessage returns a rendered message and its persistable template reference.
type MessageRef ¶
type MessageRef struct {
ID string `json:"id"`
Args map[string]any `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.
type Metric ¶
type Metric[T any] struct { Status string `json:"status"` Value *T `json:"value"` Source string `json:"source,omitempty"` Accuracy string `json:"accuracy,omitempty"` Reason *Notice `json:"reason,omitempty"` }
Metric preserves known zero and distinguishes unavailable estimates.
type MetricComparison ¶
type MetricComparison struct {
// Metric names the compared quantity. Unknown quantities stay null.
// One of: MODEL_COST, NATIVE_PLANNER_COST, ESTIMATED_ROWS_EXAMINED.
Metric string `json:"metric"`
Unit string `json:"unit"`
Scope BenefitScope `json:"scope"`
// Status states whether the two sides can be compared in one cost space.
// One of: COMPARABLE, UNAVAILABLE, NOT_COMPARABLE.
Status string `json:"status"`
Baseline *float64 `json:"baseline"`
Candidate *float64 `json:"candidate"`
AbsoluteChange *float64 `json:"absolute_change"`
ReductionPercent *float64 `json:"reduction_percent"`
ReasonCode string `json:"reason_code,omitempty"`
}
MetricComparison preserves unknown quantities as null, and known zero as zero.
type MySQLIndexProperties ¶
type MySQLIndexProperties struct {
Invisible *bool `json:"invisible"`
}
MySQLIndexProperties holds dialect-specific visibility evidence.
type NativeAccess ¶
type NativeAccess struct {
ID string `json:"id"`
PlanPath string `json:"plan_path"`
RelationLabel string `json:"relation_label"`
Target SQLTarget `json:"target"`
BindingReason string `json:"binding_reason,omitempty"`
NativeMethod string `json:"native_method"`
IndexUsed string `json:"index_used,omitempty"`
// PhysicalRelation is the qualified relation reported by EXPLAIN independently of SQL binding.
PhysicalRelation *RelationRef `json:"physical_relation,omitempty"`
// IndexKind distinguishes physical and scenario-local hypothetical indexes.
IndexKind string `json:"index_kind,omitempty"`
// ActionID identifies the scenario action used at this node, if hypothetical.
ActionID string `json:"action_id,omitempty"`
// SetBranchQueryBlockID identifies the nearest enclosing SQL set-operation branch, when bound.
SetBranchQueryBlockID string `json:"set_branch_query_block_id,omitempty"`
StartupCost *float64 `json:"startup_cost,omitempty"`
TotalCost *float64 `json:"total_cost,omitempty"`
OutputRows *float64 `json:"output_rows,omitempty"`
RowsExamined *float64 `json:"rows_examined,omitempty"`
FieldAnalysis map[string]ExplainFieldAnalysis `json:"field_analysis,omitempty"`
}
NativeAccess records one native plan occurrence separately from model costs. Target contains only proven source binding. RelationLabel retains native display text even when that occurrence cannot be mapped to a SQL source.
type NativeExplainRow ¶
type NativeExplainRow struct {
Issues []ExplainFieldResult `json:"issues,omitempty"`
Partitions string `json:"partitions,omitempty"`
Ref []string `json:"ref,omitempty"`
Extra string `json:"extra,omitempty"`
Scalability string `json:"scalability,omitempty"`
FieldAnalysis map[string]ExplainFieldAnalysis `json:"field_analysis,omitempty"`
ID int `json:"id"`
SelectType string `json:"select_type"`
RelationLabel string `json:"relation_label"`
BindingStatus string `json:"binding_status"`
NativeMethod string `json:"native_method"`
PossibleKeys []string `json:"possible_keys"`
IndexUsed string `json:"index_used,omitempty"`
KeyLength string `json:"key_length,omitempty"`
RowsExamined int64 `json:"rows_examined"`
Filtered float64 `json:"filtered"`
}
NativeExplainRow is a traditional plan row, not an executable recommendation.
type NativeExplainSummary ¶
type NativeExplainSummary struct {
Engine Engine `json:"engine"`
EngineVersion string `json:"engine_version"`
// TotalCost is nil when the engine did not report a native cost.
TotalCost *float64 `json:"total_cost,omitempty"`
RootNodeType string `json:"root_node_type"`
EstimatedRows int64 `json:"estimated_rows"`
Relations []NativeRelationAccess `json:"relations,omitempty"`
Limitations []Diagnostic `json:"limitations,omitempty"`
}
NativeExplainSummary contains stable display facts, not a planner IR.
type NativePlanReport ¶
type NativePlanReport struct {
Accesses []NativeAccess `json:"accesses,omitempty"`
Source string `json:"source"`
Engine Engine `json:"engine"`
EngineVersion string `json:"engine_version,omitempty"`
Provider string `json:"provider"`
Unit string `json:"unit"`
Summary NativeExplainSummary `json:"summary"`
StructureStatus string `json:"structure_status"`
Limitations []Notice `json:"limitations"`
}
NativePlanReport is a native estimate, separate from internal model costs.
type NativeRelationAccess ¶
type NativeRelationAccess struct {
Schema string `json:"schema,omitempty"`
Relation string `json:"relation"`
Alias string `json:"alias,omitempty"`
NativeMethod string `json:"native_method"`
IndexUsed string `json:"index_used,omitempty"`
EstimatedRows int64 `json:"estimated_rows"`
}
NativeRelationAccess summarizes access to one relation in a native plan.
type NextAction ¶
NextAction is a localizable diagnostic follow-up, not automatic execution.
type NodeEstimates ¶
type NodeEstimates struct {
TotalCost *float64 `json:"total_cost"`
StartupCost *float64 `json:"startup_cost"`
SelfCost *float64 `json:"self_cost"`
OutputRows *float64 `json:"output_rows"`
RowsExamined *float64 `json:"rows_examined"`
Invocations *float64 `json:"invocations"`
CostScope string `json:"cost_scope"`
RowScope string `json:"row_scope"`
}
NodeEstimates explicitly distinguishes subtree costs and invocation scopes.
type NodeMatch ¶
type NodeMatch struct {
BaselineID string `json:"baseline_id"`
CandidateID string `json:"candidate_id"`
Basis string `json:"basis"`
Status string `json:"status"`
}
NodeMatch declares the proven basis for a cross-plan node alignment.
type Notice ¶
type Notice struct {
ID string `json:"id"`
Code string `json:"code"`
Message Message `json:"message"`
Targets []SQLTarget `json:"targets"`
}
Notice is a controlled, localizable limitation rather than a SQL issue.
type ObservationCount ¶
ObservationCount is nullable when instrumentation is unavailable.
type Omission ¶
type Omission struct {
Scope string `json:"scope"`
ReasonCode string `json:"reason_code"`
Count *int `json:"count"`
}
Omission distinguishes unrequested, unobserved and budget-limited details.
type PlanChange ¶
type PlanChange struct {
// Kind limits the recorded change to a proven access method or index set.
// One of: ACCESS_METHOD, USED_INDEXES.
Kind string `json:"kind"`
TargetReferenceID string `json:"target_reference_id"`
AccessMethod *AccessMethodChange `json:"access_method,omitempty"`
UsedIndexes *UsedIndexesChange `json:"used_indexes,omitempty"`
}
PlanChange records only a proven aligned access-method or index change.
type PlanSummary ¶
type PlanSummary struct {
TotalCost float64 `json:"total_cost"`
StartupCost *float64 `json:"startup_cost"`
OutputRows *float64 `json:"output_rows"`
RowsExamined *float64 `json:"rows_examined"`
RootOperator string `json:"root_operator"`
Confidence *Confidence `json:"confidence,omitempty"`
}
PlanSummary holds authoritative whole-plan model quantities.
type PolicyFact ¶
type PolicyFact struct {
ID string `json:"id"`
MinimumImprovementPercent *float64 `json:"minimum_improvement_percent"`
}
PolicyFact records an effective threshold, not a display-layer default.
type PostgreSQLIndexProperties ¶
type PostgreSQLIndexProperties struct {
Ready *bool `json:"ready"`
Live *bool `json:"live"`
UniqueImmediate *bool `json:"unique_immediate"`
NullsNotDistinct *bool `json:"nulls_not_distinct"`
}
PostgreSQLIndexProperties preserves independently observed catalog flags.
type PredicateSource ¶
type PredicateSource struct {
QueryBlockID string `json:"query_block_id"`
Clause string `json:"clause"`
ClauseOrdinal int `json:"clause_ordinal"`
BranchOrdinal int `json:"branch_ordinal"`
Location Location `json:"location"`
}
PredicateSource identifies a column operand in an original SQL Boolean branch. ClauseOrdinal and BranchOrdinal are zero-based within the parser's clause list and bounded disjunction of conjunctions. They do not identify plan branches, imply pushdown, or claim that an index serves the entire branch.
type RationaleClaim ¶
type RationaleClaim struct {
Code string `json:"code"`
Message Message `json:"message"`
// Basis identifies the evidence space of this statement.
// One of: AST_BINDER, METADATA, NATIVE_PLANNER, INTERNAL_MODEL, RULE_EVIDENCE.
Basis string `json:"basis"`
EvidenceRefs []EvidenceRef `json:"evidence_refs"`
// ClaimStrength separates an observed fact from an estimate or conditional mechanism.
// One of: OBSERVED_FACT, ESTIMATE, CONDITIONAL_MECHANISM.
ClaimStrength string `json:"claim_strength"`
}
RationaleClaim qualifies the evidence space and strength of one statement.
type RawMySQLAccess ¶
type RawMySQLAccess struct {
Table, Database, PhysicalTable, Alias, PlanPath, AccessMethod, IndexUsed string
QueryBlockID int
RowsExamined, OutputRows int64
BindingStatus string
}
RawMySQLAccess is the projection input for one modeled or native access.
type RawMySQLCostChange ¶
type RawMySQLCostChange struct {
CostRatio, CostReductionPercent float64
}
RawMySQLCostChange is the relative change within one declared model.
type RawMySQLCostModelIdentity ¶
type RawMySQLCostModelIdentity struct {
Name string `json:"name"`
Version string `json:"version,omitempty"`
Profile string `json:"profile,omitempty"`
Unit string `json:"unit"`
}
RawMySQLCostModelIdentity mirrors the MySQL internal cost identity without introducing an analysis-to-optimizer dependency.
type RawMySQLDiagnostic ¶
type RawMySQLDiagnostic struct {
Code, Message, Database, Table string
}
RawMySQLDiagnostic is a non-fatal analysis limitation.
type RawMySQLIndexKeyPart ¶
type RawMySQLIndexKeyPart struct{ Column string }
RawMySQLIndexKeyPart is one ordered index key.
type RawMySQLIndexSpec ¶
type RawMySQLIndexSpec struct {
Table, Name, Method string
Unique bool
KeyParts []RawMySQLIndexKeyPart
CoveringColumns []string
}
RawMySQLIndexSpec is the projection input for one index design.
type RawMySQLIssue ¶
type RawMySQLIssue struct {
ID, Rule, Clause, Database, Table, TableAlias string
Source, Type, Category, PlanPath string
Severity Severity
Columns []string
QueryBlockID int
StartOffset, EndOffset int
StartLine, StartColumn int
Message string
MessageRef *MessageRef
Suggestions []*RawMySQLSuggestion
}
RawMySQLIssue is the neutral projection input for one MySQL rule finding.
type RawMySQLNativePlan ¶
type RawMySQLNativePlan struct {
EngineVersion string
QueryCost *float64
Accesses []RawMySQLAccess
}
RawMySQLNativePlan is the projection input for native EXPLAIN evidence.
type RawMySQLPlan ¶
type RawMySQLPlan struct {
PlanDigest string
TotalCost, StartupCost float64
OutputRows, RowsExamined int64
RootOperator string
Accesses []RawMySQLAccess
}
RawMySQLPlan is the projection input for one internal model plan.
type RawMySQLRejectedSuggestion ¶
type RawMySQLRejectedSuggestion struct {
SuggestionID string `json:"suggestion_id"`
}
RawMySQLRejectedSuggestion identifies one rejected physical design.
type RawMySQLRelationRef ¶
RawMySQLRelationRef identifies one physical MySQL relation.
type RawMySQLStructure ¶
type RawMySQLStructure struct {
Database, Table, CreateTableSQL string
}
RawMySQLStructure records the availability of one table definition.
type RawMySQLSuggestion ¶
type RawMySQLSuggestion struct {
ID, Message string
MessageRef *MessageRef
Index *RawMySQLIndexSpec
HasIndexAction bool
}
RawMySQLSuggestion is the projection input for one MySQL recommendation.
type RawMySQLWhatIf ¶
type RawMySQLWhatIf struct {
Model RawMySQLCostModelIdentity
Status, Scope string
Baseline RawMySQLPlan
Candidate RawMySQLPlan
Change RawMySQLCostChange
Warnings []RawMySQLWhatIfWarning
SelectedSuggestions []string
RejectedSuggestions []RawMySQLRejectedSuggestion
CandidateIndexes []string
}
RawMySQLWhatIf is the projection input for one whole-query comparison.
type RawMySQLWhatIfWarning ¶
type RawMySQLWhatIfWarning struct {
Code, Message string
}
RawMySQLWhatIfWarning is a non-fatal comparison limitation.
type Reason ¶
type Reason struct {
Code string `json:"code"`
Message Message `json:"message"`
Evidence []EvidenceRef `json:"evidence"`
ClaimStrength string `json:"claim_strength"`
}
Reason separates a machine code, evidence and the strength of a claim.
type Recommendation ¶
type Recommendation struct {
ID string `json:"id"`
// Kind classifies the approved proposal. COMPOSITE combines more than one action kind.
// One of: INDEX, REWRITE, OPERATIONAL, COMPOSITE.
Kind string `json:"kind"`
Priority RecommendationPriority `json:"priority"`
Title Message `json:"title"`
Summary Message `json:"summary"`
IssueIDs []string `json:"issue_ids"`
Targets []SQLTarget `json:"targets"`
Actions []RecommendedAction `json:"actions"`
Rationale RecommendationRationale `json:"rationale"`
Benefit RecommendationBenefit `json:"benefit"`
Tradeoffs RecommendationTradeoffs `json:"tradeoffs"`
Validation RecommendationValidation `json:"validation"`
Verification []VerificationStep `json:"verification"`
Decision RecommendationDecision `json:"decision"`
Relations []RecommendationRelation `json:"relations"`
Provenance RecommendationProvenance `json:"provenance"`
Limitations []Notice `json:"limitations"`
}
Recommendation is a self-contained approved proposal, not an execution grant.
type RecommendationBenefit ¶
type RecommendationBenefit struct {
// Status states whether the benefit is quantitative, qualitative, or absent.
// One of: QUANTIFIED, QUALITATIVE, UNAVAILABLE, NOT_APPLICABLE.
Status string `json:"status"`
Summary Message `json:"summary"`
Assessments []BenefitAssessment `json:"assessments"`
Limitations []Notice `json:"limitations"`
}
RecommendationBenefit is a read-only projection of authoritative comparisons.
type RecommendationDecision ¶
type RecommendationDecision struct {
// Outcome records whether the proposal is adopted or only advisory.
// One of: RECOMMEND, ADVISE.
Outcome string `json:"outcome"`
Code string `json:"code"`
Message Message `json:"message"`
PolicyChecks []RecommendationPolicyCheck `json:"policy_checks"`
}
RecommendationDecision records adoption, not candidate generation.
type RecommendationPolicyCheck ¶
type RecommendationPolicyCheck struct {
Code string `json:"code"`
Metric string `json:"metric"`
Actual float64 `json:"actual"`
// Operator is the comparison used against the recorded policy threshold.
// One of: GREATER_THAN_OR_EQUAL.
Operator string `json:"operator"`
Threshold float64 `json:"threshold"`
// Result is the recorded policy comparison outcome.
// One of: PASSED, FAILED.
Result string `json:"result"`
EvaluationID string `json:"evaluation_id"`
}
RecommendationPolicyCheck copies the effective policy and actual compared value.
type RecommendationPriority ¶
RecommendationPriority retains the engine score; rank is deterministic display order.
type RecommendationProvenance ¶
type RecommendationProvenance struct {
CandidateIDs []string `json:"candidate_ids"`
EvaluationIDs []string `json:"evaluation_ids"`
RuleCodes []string `json:"rule_codes"`
}
RecommendationProvenance closes the candidate, evaluation and rule reference chain.
type RecommendationRationale ¶
type RecommendationRationale struct {
Observations []RationaleClaim `json:"observations"`
Mechanisms []RationaleClaim `json:"mechanisms"`
}
RecommendationRationale separates observed problems from conditional mechanisms.
type RecommendationRelation ¶
type RecommendationRelation struct {
// Kind declares a recorded alternative, dependency, or conflict.
// One of: ALTERNATIVE_TO, REQUIRES, CONFLICTS_WITH.
Kind string `json:"kind"`
RecommendationID string `json:"recommendation_id"`
Message Message `json:"message"`
EvidenceRefs []EvidenceRef `json:"evidence_refs"`
}
RecommendationRelation declares recorded alternatives, dependencies or conflicts.
type RecommendationTradeoffs ¶
type RecommendationTradeoffs struct {
// Status states how much of the implementation cost was assessed.
// One of: ASSESSED, PARTIAL, NOT_ASSESSED, NOT_APPLICABLE.
Status string `json:"status"`
Items []TradeoffItem `json:"items"`
}
RecommendationTradeoffs declares assessed and unassessed implementation costs.
type RecommendationValidation ¶
type RecommendationValidation struct {
SemanticSafety ValidationRecord `json:"semantic_safety"`
ModelComparison ValidationRecord `json:"model_comparison"`
PhysicalIndex ValidationRecord `json:"physical_index"`
Runtime ValidationRecord `json:"runtime"`
}
RecommendationValidation records completed checks, separately from future work.
type RecommendedAction ¶
type RecommendedAction struct {
ID string `json:"id"`
// Kind selects the action shape projected from the candidate definition.
// One of: INDEX, REWRITE, OPERATIONAL.
Kind string `json:"kind"`
Target SQLTarget `json:"target"`
Definition ActionPayload `json:"definition"`
Execution ActionExecution `json:"execution"`
// Statement is review text, including a suggested CREATE INDEX when executable
// SQL is not available. It is not an execution grant.
Statement *Message `json:"statement,omitempty"`
Preconditions []ActionPrecondition `json:"preconditions"`
DependsOnActionIDs []string `json:"depends_on_action_ids"`
}
RecommendedAction projects the candidate definition and an approved delivery form.
type RecordedIndexCandidate ¶
type RecordedIndexCandidate struct {
SuggestionID string
Target SQLTarget
Sources []SQLTarget
Design IndexDefinition
Safe bool
}
RecordedIndexCandidate preserves a design without parsing rendered SQL.
type RecordedNativeAccess ¶
type RecordedNativeAccess struct {
Access NativeAccess
RelationOID uint32
SuggestionID string
}
RecordedNativeAccess carries native observations and their engine-side identity until SQL source binding and public report projection.
type Recording ¶
type Recording struct {
NativeAccesses []NativeAccess
PolicyIdentity string
Stages []CheckRecord
Checks []CheckRecord
Findings []*Issue
Tables []TableSnapshot
IndexCandidates []RecordedIndexCandidate
}
Recording retains evidence at its owning pipeline boundary.
type RecordingReport ¶
type RecordingReport struct {
RequestedLevel string `json:"requested_level"`
EffectiveLevel string `json:"effective_level"`
Status AnalysisStatus `json:"status"`
Collections []CollectionCount `json:"collections"`
Omissions []Omission `json:"omissions"`
}
RecordingReport reports omissions independently of analysis completeness.
type RelationIdentity ¶
type RelationIdentity struct {
Catalog string `json:"catalog,omitempty"`
Schema string `json:"schema"`
Name string `json:"name"`
Kind string `json:"kind"`
}
RelationIdentity preserves schema and identifier case.
type RelationRef ¶
type RelationRef struct {
Schema string `json:"schema,omitempty"`
Relation string `json:"relation"`
}
RelationRef identifies one physical relation without flattening its schema.
type RelativeModelCost ¶
type RelativeModelCost struct {
ModelCostRatio *float64 `json:"model_cost_ratio"`
ModelCostReductionPercent *float64 `json:"model_cost_reduction_percent"`
Interpretation CostInterpretation `json:"interpretation"`
}
RelativeModelCost is never a predicted wall-clock speedup.
type Report ¶
type Report = AnalyzeResult
Report is the engine-neutral name for the versioned report.
func NewReport ¶
func NewReport(context AnalysisContext, status AnalysisStatus) *Report
NewReport creates an empty report whose required refs remain explicit.
func (*Report) Canonicalize ¶
func (r *Report) Canonicalize()
Canonicalize normalizes report collections without rewriting ordered index keys, plan inputs, SQL targets or other order-sensitive semantic values.
func (*Report) Clone ¶
func (r *Report) Clone() *AnalyzeResult
Clone returns an isolated report snapshot, including template argument maps.
func (*Report) MarshalStable ¶
MarshalStable encodes a report after canonicalizing an isolated copy.
func (*Report) RenderMessages ¶
func (r *Report) RenderMessages(language string, render func(MessageRef, string) string)
RenderMessages re-renders persisted messages in place without re-analysis. A renderer must use the template's English default when a translation is absent.
func (*Report) ValidateReferences ¶
ValidateReferences rejects dangling references, mismatched tagged payloads, duplicate identities and cyclic merge/dependency relations.
type RequestOption ¶
type RequestOption func(*RequestOptions)
RequestOption configures one analysis request.
func WithDatabase ¶
func WithDatabase(database string) RequestOption
WithDatabase overrides the request default database. Empty preserves the Agent default.
func WithDiagnosticDetails ¶
func WithDiagnosticDetails(enabled bool) RequestOption
WithDiagnosticDetails controls whether optional diagnostic details are included in the response.
func WithExecutableRewrites ¶
func WithExecutableRewrites(enabled bool) RequestOption
WithExecutableRewrites explicitly opts one request into dialect-qualified executable SQL rewrites. The default is false.
func WithLanguage ¶
func WithLanguage(language string) RequestOption
WithLanguage selects the response language for one request.
func WithOptimizationTrace ¶
func WithOptimizationTrace(enabled bool) RequestOption
WithOptimizationTrace controls whether an engine includes its supported optimization trace details.
type RequestOptions ¶
type RequestOptions struct {
// Database is the default name-resolution context, not a relation qualifier.
Database string
// DefaultSchema is an engine-specific static namespace assumption.
DefaultSchema string
// RuleNames is an explicit request rule selection. Nil uses engine defaults.
RuleNames []string
// RuleSelectionError is set by typed engine rule-selection helpers.
RuleSelectionError error
Language string
OptimizationTrace bool
DiagnosticDetails bool
ExecutableRewrites bool
}
RequestOptions contains behavior that is meaningful for every analysis engine. Connection, sampling, and provider settings belong to engine options.
func ResolveRequestOptions ¶
func ResolveRequestOptions(options ...RequestOption) RequestOptions
ResolveRequestOptions applies options in order. Later options override earlier options for the same field.
type Result ¶
type Result struct {
Recording *Recording `json:"-"`
SQL string `json:"sql"`
Engine Engine `json:"engine"`
EngineVersion string `json:"engine_version,omitempty"`
Language string `json:"language,omitempty"`
Database string `json:"database,omitempty"`
DefaultSchema string `json:"default_schema,omitempty"`
Profile VersionProfile `json:"profile"`
Capabilities []CapabilityStatus `json:"capabilities,omitempty"`
Status AnalysisStatus `json:"status"`
Issues []*Issue `json:"issues,omitempty"`
NativeExplain *NativeExplainSummary `json:"native_explain,omitempty"`
WhatIf *WhatIfEvaluation `json:"what_if,omitempty"`
LogicalRewrites *LogicalRewriteReport `json:"logical_rewrites,omitempty"`
TablesAnalyzed []RelationRef `json:"tables_analyzed,omitempty"`
Warnings []Diagnostic `json:"warnings,omitempty"`
Unsupported []Diagnostic `json:"unsupported,omitempty"`
}
Result holds engine computation facts before report assembly.
type RewriteAttemptDiagnostic ¶
type RewriteAttemptDiagnostic struct {
ID string `json:"id"`
Definition RewriteDefinition `json:"definition"`
Stage string `json:"stage"`
Outcome string `json:"outcome"`
ReasonCode string `json:"reason_code"`
Message Message `json:"message"`
}
RewriteAttemptDiagnostic retains an attempted rewrite that was not promoted to a public candidate.
type RewriteDefinition ¶
type RewriteDefinition struct {
AttemptID string `json:"attempt_id"`
Strategy string `json:"strategy"`
Qualified bool `json:"qualified"`
Executable bool `json:"executable"`
Selected bool `json:"selected"`
SafetyStatus string `json:"safety_status"`
Diff LogicalRewriteDiff `json:"diff"`
BaselineFingerprint string `json:"baseline_fingerprint"`
CandidateFingerprint string `json:"candidate_fingerprint"`
EvidenceIdentities []string `json:"evidence_identities"`
}
RewriteDefinition retains qualification without exposing unapproved SQL.
type SQLTarget ¶
type SQLTarget struct {
PredicateSources []PredicateSource `json:"predicate_sources,omitempty"`
// Structural paths are retained for decoding; current MySQL producers omit them.
QueryBlockPath string `json:"query_block_path,omitempty"`
OccurrencePath string `json:"occurrence_path,omitempty"`
PlanPath string `json:"plan_path,omitempty"`
Alias string `json:"alias,omitempty"`
// Clause preserves the syntactic scope without claiming physical binding.
Clause string `json:"clause,omitempty"`
TableID string `json:"table_id,omitempty"`
ReferenceID string `json:"reference_id,omitempty"`
QueryBlockID string `json:"query_block_id,omitempty"`
Columns []string `json:"columns,omitempty"`
BindingStatus string `json:"binding_status"`
Location *Location `json:"location,omitempty"`
}
SQLTarget locates only proven physical bindings or explicit unresolved syntax.
type ScenarioChange ¶
ScenarioChange is one action actually applied to an isolated overlay.
type ServerVersion ¶
type ServerVersion struct {
Raw string `json:"raw,omitempty"`
Num int `json:"num,omitempty"`
Major int `json:"major,omitempty"`
Minor int `json:"minor,omitempty"`
}
ServerVersion is a stable server-version summary.
type Severity ¶
type Severity int
Severity keeps a stable 0..4 Go rank. Public JSON uses the uppercase label, matching the refactored analysis/v2 contract.
const ( // SeverityInfo reports neutral facts and exploratory findings. SeverityInfo Severity = iota // SeverityNotice reports non-blocking style and convention findings. SeverityNotice // SeverityWarning reports risks that should be corrected. SeverityWarning // SeverityError reports strongly evidenced defects that block release. SeverityError // SeverityCritical reports destructive or logically incorrect behavior. SeverityCritical )
func SeverityFromLevel ¶
SeverityFromLevel converts the stable 0..4 numeric rank to Severity.
func (Severity) MarshalJSON ¶
MarshalJSON preserves the stable public string representation.
func (*Severity) UnmarshalJSON ¶
UnmarshalJSON accepts only the five stable public strings. Numeric JSON is rejected even though Severity uses an integer representation in Go.
type SeverityPolicy ¶
SeverityPolicy contains final severity overrides keyed by a diagnostic's stable type or rule name. A type override takes precedence over a rule override when both are present.
type SubjectRef ¶
SubjectRef identifies a candidate, evaluation or finding in this report.
type Suggestion ¶
type Suggestion struct {
ID string `json:"id,omitempty"`
Type SuggestionType `json:"type"`
Priority int `json:"priority,omitempty"`
Summary string `json:"summary"`
Reason string `json:"reason,omitempty"`
Target *RelationRef `json:"target,omitempty"`
Action *Action `json:"action,omitempty"`
// SummaryRef identifies the message template that produced Summary.
SummaryRef *MessageRef `json:"summary_ref,omitempty"`
// ReasonRef identifies the message template that produced Reason.
ReasonRef *MessageRef `json:"reason_ref,omitempty"`
}
Suggestion explains a recommendation and optionally carries a safe action.
type SuggestionType ¶
type SuggestionType string
SuggestionType identifies a recommendation family.
const ( // SuggestionRewrite recommends a semantics-preserving SQL rewrite. SuggestionRewrite SuggestionType = "REWRITE" // SuggestionIndex recommends an engine-specific physical index design. SuggestionIndex SuggestionType = "INDEX" // SuggestionConfiguration recommends reviewing a runtime setting. SuggestionConfiguration SuggestionType = "CONFIGURATION" )
type TableProperties ¶
type TableProperties struct {
StorageEngine string `json:"storage_engine,omitempty"`
}
TableProperties contains collected dialect storage properties.
type TableReference ¶
type TableReference struct {
ID string `json:"id"`
QueryBlockID string `json:"query_block_id"`
Alias string `json:"alias,omitempty"`
Role string `json:"role"`
Location *Location `json:"location,omitempty"`
}
TableReference identifies one binder-owned physical-table occurrence.
type TableSnapshot ¶
type TableSnapshot struct {
ID string `json:"id"`
Identity RelationIdentity `json:"identity"`
References []TableReference `json:"references"`
Structure TableStructure `json:"structure"`
Statistics TableStatistics `json:"statistics"`
}
TableSnapshot projects only metadata already collected for this request.
func UncollectedTable ¶
func UncollectedTable(engine Engine, schema, name string) TableSnapshot
UncollectedTable records a relation identity without fabricating metadata.
type TableStatistics ¶
type TableStatistics struct {
Status string `json:"status"`
Scope []string `json:"scope"`
SnapshotID string `json:"snapshot_id,omitempty"`
Freshness string `json:"freshness"`
EstimatedRows Metric[float64] `json:"estimated_rows"`
DataBytes Metric[int64] `json:"data_bytes"`
IndexBytes Metric[int64] `json:"index_bytes"`
Columns []ColumnStatistics `json:"columns"`
Indexes []IndexStatistics `json:"indexes"`
Limitations []Notice `json:"limitations"`
}
TableStatistics never exposes samples, histogram boundaries or MCV values.
type TableStructure ¶
type TableStructure struct {
Status string `json:"status"`
Scope []string `json:"scope"`
SnapshotID string `json:"snapshot_id,omitempty"`
Columns []ColumnDefinition `json:"columns"`
Indexes []IndexDefinition `json:"indexes"`
Constraints []ConstraintDefinition `json:"constraints"`
Properties *TableProperties `json:"properties,omitempty"`
Limitations []Notice `json:"limitations"`
}
TableStructure declares its collected scope; an empty catalog is not assumed.
type TradeoffEstimate ¶
TradeoffEstimate carries a quantity with explicit units.
type TradeoffItem ¶
type TradeoffItem struct {
// Kind classifies the implementation cost being described.
// One of: STORAGE, WRITE_MAINTENANCE, DDL_OPERATION, WORKLOAD_IMPACT.
Kind string `json:"kind"`
// Assessment distinguishes an unquantified finding from a measured estimate.
// One of: NOT_QUANTIFIED, QUALITATIVE, NOT_ASSESSED, QUANTIFIED.
Assessment string `json:"assessment"`
Message Message `json:"message"`
Estimate *TradeoffEstimate `json:"estimate"`
EvidenceRefs []EvidenceRef `json:"evidence_refs"`
}
TradeoffItem never interprets an absent estimate as no risk.
type UsedIndexesChange ¶
UsedIndexesChange compares recorded indexes without inferring covering.
type ValidationRecord ¶
type ValidationRecord struct {
// Status records the check that actually ran, including checks that were not performed.
// One of: PASSED, FAILED, NOT_VALIDATED, NOT_APPLICABLE.
Status string `json:"status"`
Basis string `json:"basis,omitempty"`
Message Message `json:"message"`
EvidenceRefs []EvidenceRef `json:"evidence_refs"`
EvaluationID string `json:"evaluation_id,omitempty"`
}
ValidationRecord identifies the actual basis of a check, including unperformed checks.
type VerificationStep ¶
type VerificationStep struct {
ID string `json:"id"`
// Phase places the step before application, during controlled validation, or after.
// One of: BEFORE_APPLY, CONTROLLED_VALIDATION, AFTER_APPLY.
Phase string `json:"phase"`
Kind string `json:"kind"`
Message Message `json:"message"`
// ExecutionPolicy keeps the step manual or separately authorized. Analyze never runs it.
// One of: MANUAL_REVIEW, EXPLICIT_AUTHORIZATION_REQUIRED.
ExecutionPolicy string `json:"execution_policy"`
}
VerificationStep requests review or separately authorized validation.
type VersionProfile ¶
type VersionProfile struct {
ID string `json:"id"`
Major int `json:"major"`
Reference bool `json:"reference,omitempty"`
CostModelRevision string `json:"cost_model_revision,omitempty"`
}
VersionProfile describes the engine profile used to interpret a server.
type WhatIfEvaluation ¶
type WhatIfEvaluation struct {
Status WhatIfStatus `json:"status"`
Scope CostScope `json:"scope"`
Provider CostProvider `json:"provider"`
ModelIdentity CostModelIdentity `json:"model_identity"`
AnalysisIdentity string `json:"analysis_identity,omitempty"`
LogicalQueryFingerprint string `json:"logical_query_fingerprint,omitempty"`
CatalogIdentity string `json:"catalog_identity,omitempty"`
StatisticsIdentity string `json:"statistics_identity,omitempty"`
Baseline *CostEstimate `json:"baseline,omitempty"`
Candidates []CandidateCost `json:"candidates,omitempty"`
// CostRatio and CostReductionPercent are compatibility model summaries.
CostRatio float64 `json:"cost_ratio,omitempty"`
CostReductionPercent float64 `json:"cost_reduction_percent,omitempty"`
ModelCostRatio *float64 `json:"model_cost_ratio,omitempty"`
ModelCostReductionPercent *float64 `json:"model_cost_reduction_percent,omitempty"`
Interpretation CostInterpretation `json:"interpretation,omitempty"`
Limitations []CostLimitationCode `json:"limitations,omitempty"`
Confidence Confidence `json:"confidence,omitempty"`
SelectedSuggestions []string `json:"selected_suggestions,omitempty"`
Warnings []Diagnostic `json:"warnings,omitempty"`
Unsupported []Diagnostic `json:"unsupported,omitempty"`
}
WhatIfEvaluation is a whole-query comparison within one provider identity.
type WhatIfStatus ¶
type WhatIfStatus string
WhatIfStatus describes whether a comparison is usable.
const ( // WhatIfComplete means all selected candidates were evaluated. WhatIfComplete WhatIfStatus = "COMPLETE" // WhatIfPartial means some candidates failed or were skipped. WhatIfPartial WhatIfStatus = "PARTIAL" // WhatIfNotEvaluable means no safe comparison was possible. WhatIfNotEvaluable WhatIfStatus = "NOT_EVALUABLE" // WhatIfNotEvaluated marks a candidate that was never submitted to the planner. WhatIfNotEvaluated WhatIfStatus = "NOT_EVALUATED" // WhatIfFailed marks an attempted scenario that did not yield a usable candidate plan. WhatIfFailed WhatIfStatus = "FAILED" )