validation

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package validation provides metrics collection and export for validation operations

Package validation provides comprehensive schema validation and safety checking. It validates SQL migrations, checks for breaking changes, and ensures data integrity during migration squashing operations.

Index

Constants

View Source
const (
	RuleCodeBreakingDropColumn        = "CSQ.BREAKING.DROP_COLUMN"
	RuleCodeBreakingDropTable         = "CSQ.BREAKING.DROP_TABLE"
	RuleCodeBreakingRenameColumn      = "CSQ.BREAKING.RENAME_COLUMN"
	RuleCodeBreakingRenameTable       = "CSQ.BREAKING.RENAME_TABLE"
	RuleCodeBreakingTypeChange        = "CSQ.BREAKING.TYPE_CHANGE"
	RuleCodeSafetyConcurrentIndex     = "CSQ.SAFETY.CONCURRENT_INDEX"
	RuleCodeSafetyMissingWhere        = "CSQ.SAFETY.MISSING_WHERE"
	RuleCodeSafetyConstraintNotValid  = "CSQ.SAFETY.CONSTRAINT_NOT_VALID"
	RuleCodeSafetyConstraintFlow      = "CSQ.SAFETY.CONSTRAINT_VALIDATE_FLOW"
	RuleCodeHygienePreferText         = "CSQ.HYGIENE.PREFER_TEXT"
	RuleCodeHygienePreferBigInt       = "CSQ.HYGIENE.PREFER_BIGINT"
	RuleCodeMetaUnusedIgnoreDirective = "CSQ.META.UNUSED_IGNORE_DIRECTIVE"
)

Canonical rule identifiers for static validation.

Format:

CSQ.<DOMAIN>.<RULE_NAME>

This keeps rule IDs namespaced and stable across CLI/API/IDE surfaces.

View Source
const CatalogSnapshotContractVersion = "pgsquash.catalog-snapshot.v1"

Variables

This section is empty.

Functions

func ListRuleCodes

func ListRuleCodes() []string

ListRuleCodes returns all registered rule codes in sorted order.

func RegisterRule

func RegisterRule(rule ValidationRule)

RegisterRule registers a validation rule with the global registry

func ResolveEnabledRules

func ResolveEnabledRules(baseEnabled, enableRules, disableRules []string) ([]string, error)

ResolveEnabledRules resolves the final enabled rule set from a base config and runtime enable/disable overrides.

Behavior:

  • If baseEnabled is empty, all registered rules are considered enabled.
  • enableRules are added to the enabled set.
  • disableRules are removed from the enabled set.
  • Unknown rule codes are rejected.

func SortValidationResults

func SortValidationResults(result *ValidationResult)

SortValidationResults sorts validation results by severity and type

Types

type BanDropColumn

type BanDropColumn struct{}

func (*BanDropColumn) Category

func (r *BanDropColumn) Category() ViolationCategory

func (*BanDropColumn) Check

func (r *BanDropColumn) Check(sql string, tree *pg_query.ParseResult) ([]Violation, error)

func (*BanDropColumn) Code

func (r *BanDropColumn) Code() string

func (*BanDropColumn) Name

func (r *BanDropColumn) Name() string

type BanDropTable

type BanDropTable struct{}

func (*BanDropTable) Category

func (r *BanDropTable) Category() ViolationCategory

func (*BanDropTable) Check

func (r *BanDropTable) Check(sql string, tree *pg_query.ParseResult) ([]Violation, error)

func (*BanDropTable) Code

func (r *BanDropTable) Code() string

func (*BanDropTable) Name

func (r *BanDropTable) Name() string

type BanRenameColumn

type BanRenameColumn struct{}

func (*BanRenameColumn) Category

func (r *BanRenameColumn) Category() ViolationCategory

func (*BanRenameColumn) Check

func (r *BanRenameColumn) Check(sql string, tree *pg_query.ParseResult) ([]Violation, error)

func (*BanRenameColumn) Code

func (r *BanRenameColumn) Code() string

func (*BanRenameColumn) Name

func (r *BanRenameColumn) Name() string

type BanRenameTable

type BanRenameTable struct{}

func (*BanRenameTable) Category

func (r *BanRenameTable) Category() ViolationCategory

func (*BanRenameTable) Check

func (r *BanRenameTable) Check(sql string, tree *pg_query.ParseResult) ([]Violation, error)

func (*BanRenameTable) Code

func (r *BanRenameTable) Code() string

func (*BanRenameTable) Name

func (r *BanRenameTable) Name() string

type BanTypeChange

type BanTypeChange struct{}

func (*BanTypeChange) Category

func (r *BanTypeChange) Category() ViolationCategory

func (*BanTypeChange) Check

func (r *BanTypeChange) Check(sql string, tree *pg_query.ParseResult) ([]Violation, error)

func (*BanTypeChange) Code

func (r *BanTypeChange) Code() string

func (*BanTypeChange) Name

func (r *BanTypeChange) Name() string

type BlockMissingWhere

type BlockMissingWhere struct{}

BlockMissingWhere checks for DELETE/UPDATE statements without WHERE clauses

Rule: CSQ.SAFETY.MISSING_WHERE Category: Safety

func (*BlockMissingWhere) Category

func (r *BlockMissingWhere) Category() ViolationCategory

func (*BlockMissingWhere) Check

func (r *BlockMissingWhere) Check(sql string, tree *pg_query.ParseResult) ([]Violation, error)

func (*BlockMissingWhere) Code

func (r *BlockMissingWhere) Code() string

func (*BlockMissingWhere) Name

func (r *BlockMissingWhere) Name() string

type CatalogSnapshot

type CatalogSnapshot struct {
	ContractVersion   string   `json:"contract_version"`
	PostgreSQLVersion string   `json:"postgresql_version"`
	Signature         []string `json:"signature"`
}

CatalogSnapshot is a portable, deterministic representation of a PostgreSQL schema. It contains no connection details or data values.

type ConstraintMissingNotValid

type ConstraintMissingNotValid struct{}

ConstraintMissingNotValid checks for ADD CONSTRAINT without NOT VALID

Rule: CSQ.SAFETY.CONSTRAINT_NOT_VALID Category: Safety

func (*ConstraintMissingNotValid) Category

func (*ConstraintMissingNotValid) Check

func (*ConstraintMissingNotValid) Code

func (*ConstraintMissingNotValid) Name

type ConstraintValidateFlow

type ConstraintValidateFlow struct{}

ConstraintValidateFlow enforces NOT VALID -> VALIDATE lifecycle tracking.

Rule: CSQ.SAFETY.CONSTRAINT_VALIDATE_FLOW Category: Safety

func (*ConstraintValidateFlow) Category

func (*ConstraintValidateFlow) Check

func (*ConstraintValidateFlow) Code

func (r *ConstraintValidateFlow) Code() string

func (*ConstraintValidateFlow) Name

func (r *ConstraintValidateFlow) Name() string

type ContainerInfo

type ContainerInfo struct {
	ID   string
	Port int
}

ContainerInfo holds Docker container information

type DockerValidationResult

type DockerValidationResult struct {
	Success                 bool          `json:"success"`
	Duration                time.Duration `json:"duration"`
	Differences             string        `json:"differences,omitempty"`
	Error                   string        `json:"error,omitempty"`
	OriginalDB              string        `json:"original_db"`
	SquashedDB              string        `json:"squashed_db"`
	OriginalMigrationsError string        `json:"original_migrations_error,omitempty"` // Error applying original migrations (expected for broken migrations)
	OriginalApplyFailed     bool          `json:"original_apply_failed"`               // True when the original migrations failed to apply (comparison is unproven)
	ComparisonValid         bool          `json:"comparison_valid"`                    // True if both original and squashed migrations succeeded
	HasDifferences          bool          `json:"has_differences"`
}

DockerValidationResult represents the result of Docker-based validation.

Success is only ever true when a real comparison ran (both migration sets applied cleanly) and the schemas matched. When the original migrations fail to apply, OriginalApplyFailed is set and Success is false: equivalence is unproven, not passed.

type ExternalValidationOptions

type ExternalValidationOptions struct {
	AllowedSchemas []string
}

ExternalValidationOptions describes platform-owned schemas that may exist in an otherwise empty validation database. Extension-owned objects are always allowed because many managed Postgres services preinstall extensions.

type Fix

type Fix struct {
	Replacement string `json:"replacement"`
	Start       int32  `json:"start"` // Byte offset start (inclusive)
	End         int32  `json:"end"`   // Byte offset end (exclusive)
}

Fix represents a suggested code change

type Logger

type Logger interface {
	Infof(format string, args ...any)
	Warnf(format string, args ...any)
	Errorf(format string, args ...any)
}

Logger interface to decouple from specific logging implementation

type ObjectID

type ObjectID struct {
	Type   types.ObjectType `json:"type"`
	Schema string           `json:"schema"`
	Name   string           `json:"name"`
}

ObjectID identifies a database object

type PreferBigInt

type PreferBigInt struct{}

PreferBigInt checks for INT/INTEGER columns and suggests BIGINT

Rule: CSQ.HYGIENE.PREFER_BIGINT Category: Hygiene

func (*PreferBigInt) Category

func (r *PreferBigInt) Category() ViolationCategory

func (*PreferBigInt) Check

func (r *PreferBigInt) Check(sql string, tree *pg_query.ParseResult) ([]Violation, error)

func (*PreferBigInt) Code

func (r *PreferBigInt) Code() string

func (*PreferBigInt) Name

func (r *PreferBigInt) Name() string

type PreferText

type PreferText struct{}

func (*PreferText) Category

func (r *PreferText) Category() ViolationCategory

func (*PreferText) Check

func (r *PreferText) Check(sql string, tree *pg_query.ParseResult) ([]Violation, error)

func (*PreferText) Code

func (r *PreferText) Code() string

func (*PreferText) Name

func (r *PreferText) Name() string

type RequireConcurrentIndex

type RequireConcurrentIndex struct{}

func (*RequireConcurrentIndex) Category

func (*RequireConcurrentIndex) Check

func (*RequireConcurrentIndex) Code

func (r *RequireConcurrentIndex) Code() string

func (*RequireConcurrentIndex) Name

func (r *RequireConcurrentIndex) Name() string

type RuleRegistry

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

RuleRegistry manages the available validation rules

func (*RuleRegistry) Get

func (r *RuleRegistry) Get(code string) (ValidationRule, bool)

Get retrieves a rule by its code

func (*RuleRegistry) GetAll

func (r *RuleRegistry) GetAll() []ValidationRule

GetAll returns all registered rules

func (*RuleRegistry) Register

func (r *RuleRegistry) Register(rule ValidationRule)

Register adds a rule to the registry

type SchemaComparator

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

SchemaComparator compares two live PostgreSQL schemas using catalog signatures.

func NewSchemaComparator

func NewSchemaComparator(logger Logger) *SchemaComparator

NewSchemaComparator creates a new schema comparator

func (*SchemaComparator) CompareDatabases

func (sc *SchemaComparator) CompareDatabases(ctx context.Context, sourceDB, targetDB *sql.DB) (*SchemaDiff, error)

CompareDatabases compares two databases and returns a detailed difference report.

This implementation intentionally avoids external schema-diff engines and uses deterministic catalog signatures gathered directly from each database.

type SchemaComparisonResult

type SchemaComparisonResult struct {
	TablesMatch     bool               `json:"tables_match"`
	IndexesMatch    bool               `json:"indexes_match"`
	FunctionsMatch  bool               `json:"functions_match"`
	ExtensionsMatch bool               `json:"extensions_match"`
	Differences     []SchemaDifference `json:"differences"`
	Summary         string             `json:"summary"`
}

SchemaComparisonResult provides detailed schema differences

type SchemaDiff

type SchemaDiff struct {
	HasDifferences bool
	Differences    []string
}

SchemaDiff represents differences between schemas

func CompareCatalogSnapshots

func CompareCatalogSnapshots(original, candidate *CatalogSnapshot) (*SchemaDiff, error)

CompareCatalogSnapshots compares two previously captured catalog snapshots.

func CompareSchemasDirectly

func CompareSchemasDirectly(schema1, schema2 string) (*SchemaDiff, error)

CompareSchemasDirectly compares two schema SQL strings directly using normalized statement sets.

type SchemaDifference

type SchemaDifference struct {
	Type       string `json:"type"` // TABLE, INDEX, FUNCTION, etc.
	Name       string `json:"name"`
	Difference string `json:"difference"` // MISSING, EXTRA, MODIFIED
	Details    string `json:"details"`
	Severity   string `json:"severity"` // LOW, MEDIUM, HIGH, CRITICAL
}

SchemaDifference represents a specific schema difference

type SchemaValidator

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

SchemaValidator performs comprehensive schema validation including Docker-based validation

func NewSchemaValidator

func NewSchemaValidator(config *ValidationConfig, db *sql.DB, reporter performance.ProgressReporter) *SchemaValidator

NewSchemaValidator creates a new schema validator

func (*SchemaValidator) ApplyAndSnapshot

func (sv *SchemaValidator) ApplyAndSnapshot(
	ctx context.Context,
	migrationPath, dsn string,
	options ...ExternalValidationOptions,
) (*CatalogSnapshot, error)

ApplyAndSnapshot applies a migration path to a caller-owned empty database and returns its catalog signature. It refuses to touch a non-empty database. The caller remains responsible for provisioning and deleting the database.

func (*SchemaValidator) Close

func (sv *SchemaValidator) Close() error

Close closes the validator and its resources

func (*SchemaValidator) Errorf

func (sv *SchemaValidator) Errorf(format string, args ...any)

func (*SchemaValidator) Infof

func (sv *SchemaValidator) Infof(format string, args ...any)

Ensure SchemaValidator implements Logger interface

func (*SchemaValidator) ValidateMigrations

func (sv *SchemaValidator) ValidateMigrations(ctx context.Context, migrations []*types.Migration) (*ValidationResult, error)

ValidateMigrations validates a set of migrations

func (*SchemaValidator) ValidateWithDocker

func (sv *SchemaValidator) ValidateWithDocker(ctx context.Context, originalPath, squashedPath string) (*ValidationResult, error)

ValidateWithDocker validates squashed migrations using Docker containers

func (*SchemaValidator) Warnf

func (sv *SchemaValidator) Warnf(format string, args ...any)

type StaticValidator

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

StaticValidator performs AST-based checking of SQL

func NewStaticValidator

func NewStaticValidator(conf *config.StaticValidatorConfig) *StaticValidator

NewStaticValidator creates a validator with the configured rules

func (*StaticValidator) ApplyFixes

func (v *StaticValidator) ApplyFixes(sql string, violations []Violation) (string, error)

ApplyFixes applies the fixes from the given violations to the SQL string

func (*StaticValidator) Check

func (v *StaticValidator) Check(sql string) ([]Violation, error)

Check parses the SQL and runs all configured rules against the AST

type ValidationApproach

type ValidationApproach string

ValidationApproach defines Docker-based validation strategies

const (
	ApproachTwoContainers ValidationApproach = "TWO_CONTAINERS" // Most accurate
	ApproachTwoDatabases  ValidationApproach = "TWO_DATABASES"  // Best balance
	ApproachSchemaDiff    ValidationApproach = "SCHEMA_DIFF"    // Fastest
)

type ValidationConfig

type ValidationConfig struct {
	Level                ValidationLevel `json:"level"`
	DatabaseURL          string          `json:"database_url,omitempty"`
	ValidateExpressions  bool            `json:"validate_expressions"`
	ValidateConstraints  bool            `json:"validate_constraints"`
	ValidateDependencies bool            `json:"validate_dependencies"`
	ValidatePermissions  bool            `json:"validate_permissions"`
	ValidatePerformance  bool            `json:"validate_performance"`
	IgnoreWarnings       bool            `json:"ignore_warnings"`
	StopOnError          bool            `json:"stop_on_error"`
	MaxConcurrentQueries int             `json:"max_concurrent_queries"`
	QueryTimeout         time.Duration   `json:"query_timeout"`
	// Docker-based validation options
	DockerApproach           ValidationApproach `json:"docker_approach,omitempty"`
	PostgreSQLVersion        string             `json:"postgresql_version,omitempty"`  // PostgreSQL version for validation containers (default: 17)
	CustomDockerImage        string             `json:"custom_docker_image,omitempty"` // Custom Docker image with pre-installed extensions (e.g., "myregistry/postgres-postgis:17")
	EnableExtensionDetection bool               `json:"enable_extension_detection"`
	AutoInstallExtensions    bool               `json:"auto_install_extensions"`
	EnableSQLFixes           bool               `json:"enable_sql_fixes"`
	EnablePreprocessing      bool               `json:"enable_preprocessing"` // Preprocess SQL to fix common issues (e.g., deduplicate publication statements) (default: true)
	CustomExtensions         map[string]string  `json:"custom_extensions,omitempty"`
	Verbose                  bool               `json:"verbose"`
	ContainerReadyTimeout    time.Duration      `json:"container_ready_timeout,omitempty"`  // Timeout for container readiness (default: 150s, recommended for complex migrations with many extensions)
	MaxPortSearchAttempts    int                `json:"max_port_search_attempts,omitempty"` // Max ports to search (default: 1000)
	AuthCompatibilitySQL     string             `json:"auth_compatibility_sql,omitempty"`   // Auth compatibility SQL to inject before migrations
}

ValidationConfig configures validation behavior

func DefaultValidationConfig

func DefaultValidationConfig() *ValidationConfig

DefaultValidationConfig returns a default validation configuration

type ValidationError

type ValidationError struct {
	Code       string         `json:"code"`
	Message    string         `json:"message"`
	ObjectID   ObjectID       `json:"object_id"`
	Severity   string         `json:"severity"`
	Context    map[string]any `json:"context,omitempty"`
	Suggestion string         `json:"suggestion,omitempty"`
	SQLQuery   string         `json:"sql_query,omitempty"`
	Line       int            `json:"line,omitempty"`
	File       string         `json:"file,omitempty"`
}

ValidationError represents a validation error This now wraps the unified StructuredError

type ValidationFix

type ValidationFix struct {
	Issue       string `json:"issue"`
	Fix         string `json:"fix"`
	Success     bool   `json:"success"`
	Description string `json:"description"`
}

ValidationFix represents a fix applied during validation

type ValidationLevel

type ValidationLevel string

ValidationLevel represents the level of validation to perform

const (
	ValidationLevelBasic         ValidationLevel = "BASIC"
	ValidationLevelStandard      ValidationLevel = "STANDARD"
	ValidationLevelThorough      ValidationLevel = "THOROUGH"
	ValidationLevelComprehensive ValidationLevel = "COMPREHENSIVE"
)

type ValidationMetrics

type ValidationMetrics struct {

	// Timing metrics
	TotalDuration        time.Duration `json:"total_duration_ms"`
	ValidationStartTime  time.Time     `json:"validation_start_time"`
	ValidationEndTime    time.Time     `json:"validation_end_time"`
	AverageQueryDuration time.Duration `json:"average_query_duration_ms"`
	SlowestQueryDuration time.Duration `json:"slowest_query_duration_ms"`

	// Count metrics
	TotalValidations      int64 `json:"total_validations"`
	SuccessfulValidations int64 `json:"successful_validations"`
	FailedValidations     int64 `json:"failed_validations"`
	ObjectsValidated      int64 `json:"objects_validated"`
	QueriesExecuted       int64 `json:"queries_executed"`
	ErrorsFound           int64 `json:"errors_found"`
	WarningsFound         int64 `json:"warnings_found"`

	// Schema metrics
	TablesValidated      int64 `json:"tables_validated"`
	IndexesValidated     int64 `json:"indexes_validated"`
	FunctionsValidated   int64 `json:"functions_validated"`
	TriggersValidated    int64 `json:"triggers_validated"`
	ConstraintsValidated int64 `json:"constraints_validated"`
	ViewsValidated       int64 `json:"views_validated"`
	ExtensionsDetected   int64 `json:"extensions_detected"`

	// Docker validation metrics
	DockerContainersSpun int64         `json:"docker_containers_spun"`
	DockerValidationTime time.Duration `json:"docker_validation_time_ms"`
	DockerFailures       int64         `json:"docker_failures"`

	// Error breakdown
	ErrorsByCode     map[string]int64 `json:"errors_by_code"`
	ErrorsBySeverity map[string]int64 `json:"errors_by_severity"`

	// Warning breakdown
	WarningsByCode map[string]int64 `json:"warnings_by_code"`

	// Validation approach metrics
	ApproachUsage map[string]int64 `json:"approach_usage"` // TWO_CONTAINERS, TWO_DATABASES, SCHEMA_DIFF

	// Extension metrics
	ExtensionInstallAttempts int64         `json:"extension_install_attempts"`
	ExtensionInstallFailures int64         `json:"extension_install_failures"`
	ExtensionInstallTime     time.Duration `json:"extension_install_time_ms"`

	// SQL fix metrics
	FixesAttempted int64 `json:"fixes_attempted"`
	FixesSucceeded int64 `json:"fixes_succeeded"`
	FixesFailed    int64 `json:"fixes_failed"`

	// Resource metrics
	PeakMemoryUsage int64         `json:"peak_memory_bytes"`
	CPUTimeUsed     time.Duration `json:"cpu_time_ms"`

	// Metadata
	ValidationLevel   string    `json:"validation_level"`
	PostgreSQLVersion string    `json:"postgresql_version"`
	LastUpdated       time.Time `json:"last_updated"`
	// contains filtered or unexported fields
}

ValidationMetrics provides comprehensive validation metrics with export capabilities

func NewValidationMetrics

func NewValidationMetrics() *ValidationMetrics

NewValidationMetrics creates a new validation metrics collector

func (*ValidationMetrics) ExportJSON

func (m *ValidationMetrics) ExportJSON(w io.Writer) error

ExportJSON exports metrics as JSON

func (*ValidationMetrics) ExportPrometheus

func (m *ValidationMetrics) ExportPrometheus(w io.Writer) error

ExportPrometheus exports metrics in Prometheus format

func (*ValidationMetrics) GetSnapshot

func (m *ValidationMetrics) GetSnapshot() *ValidationMetrics

GetSnapshot returns a thread-safe copy of metrics

func (*ValidationMetrics) RecordDockerValidation

func (m *ValidationMetrics) RecordDockerValidation(approach string, duration time.Duration, success bool)

RecordDockerValidation records Docker validation metrics

func (*ValidationMetrics) RecordError

func (m *ValidationMetrics) RecordError(code, severity string)

RecordError records an error

func (*ValidationMetrics) RecordExtensionInstall

func (m *ValidationMetrics) RecordExtensionInstall(success bool, duration time.Duration)

RecordExtensionInstall records extension installation attempt

func (*ValidationMetrics) RecordFix

func (m *ValidationMetrics) RecordFix(success bool)

RecordFix records a SQL fix attempt

func (*ValidationMetrics) RecordQuery

func (m *ValidationMetrics) RecordQuery(duration time.Duration)

RecordQuery records a query execution

func (*ValidationMetrics) RecordSchemaObject

func (m *ValidationMetrics) RecordSchemaObject(objectType string)

RecordSchemaObject records a validated schema object

func (*ValidationMetrics) RecordValidation

func (m *ValidationMetrics) RecordValidation(success bool, duration time.Duration)

RecordValidation records a completed validation

func (*ValidationMetrics) RecordWarning

func (m *ValidationMetrics) RecordWarning(code string)

RecordWarning records a warning

func (*ValidationMetrics) Reset

func (m *ValidationMetrics) Reset()

Reset resets all metrics to zero

func (*ValidationMetrics) SetPostgreSQLVersion

func (m *ValidationMetrics) SetPostgreSQLVersion(version string)

SetPostgreSQLVersion sets the PostgreSQL version metadata

func (*ValidationMetrics) SetValidationLevel

func (m *ValidationMetrics) SetValidationLevel(level string)

SetValidationLevel sets the validation level metadata

func (*ValidationMetrics) SetValidationTimes

func (m *ValidationMetrics) SetValidationTimes(start, end time.Time)

SetValidationTimes sets validation start and end times

func (*ValidationMetrics) UpdateResourceMetrics

func (m *ValidationMetrics) UpdateResourceMetrics(memoryBytes int64, cpuTime time.Duration)

UpdateResourceMetrics updates resource usage metrics

type ValidationResult

type ValidationResult struct {
	StartTime time.Time           `json:"start_time"`
	EndTime   time.Time           `json:"end_time"`
	Duration  time.Duration       `json:"duration"`
	Level     ValidationLevel     `json:"level"`
	Success   bool                `json:"success"`
	Errors    []ValidationError   `json:"errors"`
	Warnings  []ValidationWarning `json:"warnings"`

	Statistics ValidationStatistics `json:"statistics"`
	Details    map[string]any       `json:"details,omitempty"`
	// Docker validation results
	DockerValidation    *DockerValidationResult `json:"docker_validation,omitempty"`
	ExtensionsDetected  []string                `json:"extensions_detected,omitempty"`
	ExtensionsInstalled []string                `json:"extensions_installed,omitempty"`
	ApproachUsed        ValidationApproach      `json:"approach_used,omitempty"`
	FixesApplied        []ValidationFix         `json:"fixes_applied,omitempty"`
}

ValidationResult represents the result of schema validation

type ValidationRule

type ValidationRule interface {
	Code() string
	Name() string
	Category() ViolationCategory
	Check(sql string, tree *pg_query.ParseResult) ([]Violation, error)
}

ValidationRule defines the interface for static validation rules

func GetAllRules

func GetAllRules() []ValidationRule

GetAllRules returns all registered rules

func GetRule

func GetRule(code string) (ValidationRule, bool)

GetRule returns a rule by its code

type ValidationStatistics

type ValidationStatistics struct {
	ObjectsValidated     int `json:"objects_validated"`
	QueriesExecuted      int `json:"queries_executed"`
	ExpressionsValidated int `json:"expressions_validated"`
	ConstraintsChecked   int `json:"constraints_checked"`
	DependenciesResolved int `json:"dependencies_resolved"`
	ErrorsFound          int `json:"errors_found"`
	WarningsFound        int `json:"warnings_found"`
}

ValidationStatistics provides validation statistics

type ValidationWarning

type ValidationWarning struct {
	Code       string         `json:"code"`
	Message    string         `json:"message"`
	ObjectID   ObjectID       `json:"object_id"`
	Context    map[string]any `json:"context,omitempty"`
	Suggestion string         `json:"suggestion,omitempty"`
}

ValidationWarning represents a validation warning

type Violation

type Violation struct {
	Code       string            `json:"code"`
	Message    string            `json:"message"`
	Category   ViolationCategory `json:"category"`
	Statement  string            `json:"statement,omitempty"`
	Line       int32             `json:"line,omitempty"`
	StmtStart  int32             `json:"stmt_start,omitempty"`
	StmtEnd    int32             `json:"stmt_end,omitempty"`
	Suggestion string            `json:"suggestion,omitempty"`
	Fix        *Fix              `json:"fix,omitempty"`
}

Violation represents a rule violation found during static analysis

type ViolationCategory

type ViolationCategory string

ViolationCategory represents the severity/type of a violation

const (
	CategorySafety   ViolationCategory = "safety"
	CategoryBreaking ViolationCategory = "breaking"
	CategoryHygiene  ViolationCategory = "hygiene"
)

Jump to

Keyboard shortcuts

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