types

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: 8 Imported by: 0

Documentation

Overview

Package types contains shared type definitions used across multiple packages. This avoids import cycles between parser, plugins, tracking, and other packages.

Package types provides PostgreSQL type system analysis and management. It handles type compatibility checking, custom type analysis, and database type introspection for migration squashing operations.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ArrayType

type ArrayType struct {
	Schema      string `json:"schema"`
	Name        string `json:"name"`
	ElementType string `json:"element_type"`
	Dimensions  int    `json:"dimensions"`
}

ArrayType represents an array type

type Attribute

type Attribute struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	NotNull  bool   `json:"not_null"`
	Default  string `json:"default"`
	Position int    `json:"position"`
}

Attribute represents an attribute of a composite type

type AuthPatternType

type AuthPatternType string

AuthPatternType represents detected authentication/authorization patterns. Plugins provide specific identifiers (e.g., "clerk_jwt_v2", "supabase_rls"). The parser delegates auth pattern detection to the plugin layer.

const (
	AuthPatternNone    AuthPatternType = ""
	AuthPatternRLS     AuthPatternType = "RLS_POLICY"     // Row-Level Security policies
	AuthPatternStorage AuthPatternType = "STORAGE_POLICY" // Storage bucket policies
	AuthPatternJWT     AuthPatternType = "JWT_AUTH"       // JWT-based authentication
	AuthPatternSession AuthPatternType = "SESSION_AUTH"   // Session-based authentication
	AuthPatternCustom  AuthPatternType = "CUSTOM_AUTH"    // Custom authentication
)

Generic auth pattern categories used when filtering generic auth rules.

type CastType

type CastType int

CastType defines the type of cast required

const (
	NoCast CastType = iota
	ImplicitCast
	AssignmentCast
	ExplicitCast
)

type Category

type Category string

Category represents the semantic category of a statement for organization

const (
	CategoryFoundation  Category = "foundation"  // Schemas, extensions, base types
	CategoryConstraints Category = "constraints" // Foreign keys, checks, unique constraints
	CategoryIndexes     Category = "indexes"     // Indexes and index-like objects
	CategoryFunctions   Category = "functions"   // Functions, procedures, triggers
	CategoryTriggers    Category = "triggers"    // Trigger definitions
	CategoryComments    Category = "comments"    // COMMENT ON statements (must come after objects)
	CategorySecurity    Category = "security"    // RLS policies, grants, roles
	CategoryData        Category = "data"        // INSERT, UPDATE, DELETE statements
	CategoryExtensions  Category = "extensions"  // PostgreSQL extensions
	CategoryCritical    Category = "critical"    // Critical statements that should never be modified
)

type CompatibilityLevel

type CompatibilityLevel int

CompatibilityLevel defines the level of compatibility

const (
	FullyCompatible CompatibilityLevel = iota
	MostlyCompatible
	PartiallyCompatible
	Incompatible
)

type CompositeType

type CompositeType struct {
	Schema     string      `json:"schema"`
	Name       string      `json:"name"`
	Attributes []Attribute `json:"attributes"`
}

CompositeType represents a composite (row) type

type Constraint

type Constraint struct {
	Name       string `json:"name"`
	Expression string `json:"expression"`
	Validated  bool   `json:"validated"`
}

Constraint represents a domain constraint

type ContextType

type ContextType int

ContextType defines where a type is used

const (
	TableColumnContext ContextType = iota
	FunctionParameterContext
	FunctionReturnContext
	DomainBaseContext
	CompositeAttributeContext
	ArrayElementContext
	IndexExpressionContext
)

type CrossSchemaRef

type CrossSchemaRef struct {
	Schema     string     // Referenced schema name
	ObjectType ObjectType // Type of referenced object
	ObjectName string     // Name of referenced object
}

CrossSchemaRef represents a reference to an object in a different schema

type CustomType

type CustomType struct {
	Schema      string            `json:"schema"`
	Name        string            `json:"name"`
	BaseType    string            `json:"base_type"`
	Category    TypeCategory      `json:"category"`
	Attributes  map[string]string `json:"attributes"`
	Constraints []string          `json:"constraints"`
}

CustomType represents a user-defined type

type DependencyType

type DependencyType int

DependencyType defines the type of dependency relationship

const (
	CompositionDependency DependencyType = iota
	InheritanceDependency
	ArrayElementDependency
	DomainBaseDependency
	FunctionParameterDependency
	TableColumnDependency
)

type Domain

type Domain struct {
	Schema      string       `json:"schema"`
	Name        string       `json:"name"`
	BaseType    string       `json:"base_type"`
	NotNull     bool         `json:"not_null"`
	Default     string       `json:"default"`
	Constraints []Constraint `json:"constraints"`
}

Domain represents a PostgreSQL domain

type EnumType

type EnumType struct {
	Schema string   `json:"schema"`
	Name   string   `json:"name"`
	Values []string `json:"values"`
}

EnumType represents an enumerated type

type ExecutionTimeCategory

type ExecutionTimeCategory string

ExecutionTimeCategory estimates how long a statement might take

const (
	ExecutionInstant ExecutionTimeCategory = "INSTANT" // < 1ms (most DDL on empty tables)
	ExecutionFast    ExecutionTimeCategory = "FAST"    // < 100ms
	ExecutionMedium  ExecutionTimeCategory = "MEDIUM"  // < 1s
	ExecutionSlow    ExecutionTimeCategory = "SLOW"    // > 1s (backfills, large indexes)
	ExecutionUnknown ExecutionTimeCategory = "UNKNOWN"
)

type LockLevel

type LockLevel string

LockLevel represents the PostgreSQL lock level required by a statement

const (
	LockNone                 LockLevel = "NONE"                   // No lock required
	LockAccessShare          LockLevel = "ACCESS_SHARE"           // SELECT
	LockRowShare             LockLevel = "ROW_SHARE"              // SELECT FOR UPDATE/SHARE
	LockRowExclusive         LockLevel = "ROW_EXCLUSIVE"          // INSERT, UPDATE, DELETE
	LockShareUpdateExclusive LockLevel = "SHARE_UPDATE_EXCLUSIVE" // VACUUM, CREATE INDEX CONCURRENTLY
	LockShare                LockLevel = "SHARE"                  // CREATE INDEX (non-concurrent)
	LockShareRowExclusive    LockLevel = "SHARE_ROW_EXCLUSIVE"    // Rare, some ALTER TABLE
	LockExclusive            LockLevel = "EXCLUSIVE"              // REFRESH MATERIALIZED VIEW CONCURRENTLY
	LockAccessExclusive      LockLevel = "ACCESS_EXCLUSIVE"       // Most DDL, TRUNCATE, VACUUM FULL
)

type Migration

type Migration struct {
	Filename    string      // Migration filename
	Sequence    int         // Migration sequence number
	Statements  []Statement // Parsed SQL statements
	Size        int64       // File size in bytes
	ParseErrors []string    // Parse errors encountered during migration parsing
}

Migration represents a parsed migration file with metadata and statements

type MigrationTypeAnalysis

type MigrationTypeAnalysis struct {
	TypesUsed    map[string]*TypeInfo `json:"types_used"`
	TypeChanges  []*TypeChange        `json:"type_changes"`
	Dependencies []*TypeDependency    `json:"dependencies"`
	Warnings     []string             `json:"warnings"`
}

MigrationTypeAnalysis represents the result of analyzing types in a migration

type ObjectType

type ObjectType string

ObjectType represents the type of database object

const (
	TypeTable           ObjectType = "TABLE"
	TypeIndex           ObjectType = "INDEX"
	TypeFunction        ObjectType = "FUNCTION"
	TypeTrigger         ObjectType = "TRIGGER"
	TypeView            ObjectType = "VIEW"
	TypeSequence        ObjectType = "SEQUENCE"
	TypeConstraint      ObjectType = "CONSTRAINT"
	TypePolicy          ObjectType = "POLICY"
	TypeRole            ObjectType = "ROLE"
	TypeSchema          ObjectType = "SCHEMA"
	TypeExtension       ObjectType = "EXTENSION"
	TypePublication     ObjectType = "PUBLICATION"
	TypeComment         ObjectType = "COMMENT"
	TypeDoBlock         ObjectType = "DO_BLOCK"
	TypeType            ObjectType = "TYPE"             // CREATE TYPE statements (enums, composites, domains)
	TypeDomain          ObjectType = "DOMAIN"           // CREATE DOMAIN statements
	TypeEnum            ObjectType = "ENUM"             // CREATE TYPE ... AS ENUM statements
	TypeComposite       ObjectType = "COMPOSITE"        // CREATE TYPE ... AS (composite types)
	TypeSubscription    ObjectType = "SUBSCRIPTION"     // PostgreSQL 15+
	TypeStatistic       ObjectType = "STATISTIC"        // PostgreSQL 15+
	TypeGeneratedColumn ObjectType = "GENERATED_COLUMN" // PostgreSQL 15+
	TypeMultirangeType  ObjectType = "MULTIRANGE_TYPE"  // PostgreSQL 14+
	TypeVectorIndex     ObjectType = "VECTOR_INDEX"     // pgvector extension
	TypeEventTrigger    ObjectType = "EVENT_TRIGGER"    // PostgreSQL 17+
	TypeData            ObjectType = "DATA"             // Data operations (INSERT, UPDATE, DELETE)
	TypeUnknown         ObjectType = "UNKNOWN"
)

type Operation

type Operation string

Operation represents the SQL operation being performed

const (
	OpCreate  Operation = "CREATE"
	OpAlter   Operation = "ALTER"
	OpDrop    Operation = "DROP"
	OpInsert  Operation = "INSERT"
	OpUpdate  Operation = "UPDATE"
	OpDelete  Operation = "DELETE"
	OpGrant   Operation = "GRANT"
	OpRevoke  Operation = "REVOKE"
	OpComment Operation = "COMMENT"
)

type PostgreSQLTypeSystem

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

PostgreSQLTypeSystem handles PostgreSQL-specific type operations and conversions

func NewPostgreSQLTypeSystem

func NewPostgreSQLTypeSystem(version string) *PostgreSQLTypeSystem

NewPostgreSQLTypeSystem creates a new PostgreSQL type system

func (*PostgreSQLTypeSystem) CheckTypeCompatibility

func (pts *PostgreSQLTypeSystem) CheckTypeCompatibility(fromType, toType string) *TypeCompatibility

CheckTypeCompatibility checks compatibility between two types

func (*PostgreSQLTypeSystem) GetCompositeTypeAttributes

func (pts *PostgreSQLTypeSystem) GetCompositeTypeAttributes(typeName string) ([]Attribute, error)

GetCompositeTypeAttributes returns the attributes of a composite type

func (*PostgreSQLTypeSystem) GetTypeSize

func (pts *PostgreSQLTypeSystem) GetTypeSize(typeName string) (int, error)

GetTypeSize estimates the storage size of a type

func (*PostgreSQLTypeSystem) IsBuiltinType

func (pts *PostgreSQLTypeSystem) IsBuiltinType(typeName string) bool

IsBuiltinType checks if a type is a PostgreSQL built-in type

func (*PostgreSQLTypeSystem) IsCompatibleArrayDimensions

func (pts *PostgreSQLTypeSystem) IsCompatibleArrayDimensions(from, to *ArrayType) bool

IsCompatibleArrayDimensions checks if array dimensions are compatible

func (*PostgreSQLTypeSystem) ParseArrayType

func (pts *PostgreSQLTypeSystem) ParseArrayType(typeSpec string) (*ArrayType, error)

ParseArrayType parses an array type specification

func (*PostgreSQLTypeSystem) RegisterCompositeType

func (pts *PostgreSQLTypeSystem) RegisterCompositeType(compositeType *CompositeType)

RegisterCompositeType registers a composite type in the system

func (*PostgreSQLTypeSystem) RegisterCustomType

func (pts *PostgreSQLTypeSystem) RegisterCustomType(customType *CustomType)

RegisterCustomType registers a custom type in the system

func (*PostgreSQLTypeSystem) RegisterDomain

func (pts *PostgreSQLTypeSystem) RegisterDomain(domain *Domain)

RegisterDomain registers a domain in the system

func (*PostgreSQLTypeSystem) RegisterEnumType

func (pts *PostgreSQLTypeSystem) RegisterEnumType(enumType *EnumType)

RegisterEnumType registers an enum type in the system

func (*PostgreSQLTypeSystem) ValidateEnumValue

func (pts *PostgreSQLTypeSystem) ValidateEnumValue(enumTypeName, value string) error

ValidateEnumValue validates that a value is valid for an enum type

type RangeType

type RangeType struct {
	Schema         string `json:"schema"`
	Name           string `json:"name"`
	SubType        string `json:"sub_type"`
	SubTypeOpClass string `json:"sub_type_op_class"`
	Collation      string `json:"collation"`
	Canonical      string `json:"canonical"`
	SubTypeDiff    string `json:"sub_type_diff"`
}

RangeType represents a range type

type Statement

type Statement struct {
	SQL          string                // Original SQL text
	ParseTree    *pg_query.ParseResult // Parse tree containing the raw AST
	Filename     string                // Source filename for this statement
	ObjectType   ObjectType            // Type of database object (TABLE, INDEX, FUNCTION, etc.)
	ObjectName   string                // Name of the object being operated on
	Operation    Operation             // SQL operation (CREATE, ALTER, DROP, etc.)
	Line         int                   // Line number in migration file
	Column       int                   // Column number in migration file
	IsDataOp     bool                  // Whether this is a data operation (INSERT, UPDATE, DELETE)
	Category     Category              // Statement category for organization
	Dependencies []string              // Object dependencies (foreign keys, function calls, etc.)
	Comments     []string              // Associated SQL comments
	Schema       string                // Schema name (defaults to "public")
	CrossSchema  []CrossSchemaRef      // Cross-schema references
	AuthPattern  AuthPatternType       // Detected authentication pattern
	IsDynamic    bool                  // Whether SQL contains dynamic elements
	IfNotExists  bool                  // Whether statement uses IF NOT EXISTS clause

	// GRANT/REVOKE specific fields
	Grantees   []string // Users/roles receiving permissions
	Privileges []string // Privileges being granted/revoked

	// ALTER TYPE specific fields
	AlterTypeNewValue string // New ENUM value being added via ALTER TYPE ADD VALUE

	// Index specific fields
	IndexHadExplicitAccessMethod bool // Whether CREATE INDEX had explicit USING clause

	// Statement metadata for transaction and lock analysis
	Metadata StatementMetadata
}

Statement represents a single parsed SQL statement with rich metadata

Note: ParseTree is kept as interface{} to avoid circular dependencies. In practice, this is typically *pg_query.ParseResult from the parser package. Plugins and other packages should use SQL and metadata fields instead of ParseTree.

type StatementMetadata

type StatementMetadata struct {
	// Lock level required by this statement
	LockLevel LockLevel

	// Whether this statement cannot run inside a transaction
	RequiresNoTransaction bool

	// PostgreSQL version gate (e.g., "PG<12" for ENUM additions)
	VersionGate string

	// Whether this is a concurrent operation
	Concurrent bool

	// Whether this statement should be preserved verbatim (manual pragma)
	PreserveVerbatim bool

	// Estimated execution time category
	ExecutionTime ExecutionTimeCategory

	// Whether this statement is idempotent
	Idempotent bool
}

StatementMetadata contains metadata about statement execution requirements

type TypeAnalyzer

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

TypeAnalyzer analyzes PostgreSQL types in SQL statements and migrations

func NewTypeAnalyzer

func NewTypeAnalyzer(typeSystem *PostgreSQLTypeSystem, db *sql.DB) *TypeAnalyzer

NewTypeAnalyzer creates a new type analyzer

func (*TypeAnalyzer) AnalyzeMigrationTypes

func (ta *TypeAnalyzer) AnalyzeMigrationTypes(ctx context.Context, statements []Statement) (*MigrationTypeAnalysis, error)

AnalyzeMigrationTypes analyzes all types used in a migration

func (*TypeAnalyzer) AnalyzeStatement

func (ta *TypeAnalyzer) AnalyzeStatement(ctx context.Context, sql string) ([]*TypeInfo, error)

AnalyzeStatement analyzes types used in a SQL statement

func (*TypeAnalyzer) GenerateTypeConversion

func (ta *TypeAnalyzer) GenerateTypeConversion(ctx context.Context, fromType, toType string, columnName string) (*TypeConversion, error)

GenerateTypeConversion generates SQL for type conversion

type TypeCategory

type TypeCategory int

TypeCategory categorizes PostgreSQL types

const (
	BaseType TypeCategory = iota
	DomainType
	CompositeTypeCategory
	EnumTypeCategory
	ArrayTypeCategory
	RangeTypeCategory
	PseudoType
)

type TypeChange

type TypeChange struct {
	Table      string `json:"table"`
	Column     string `json:"column"`
	FromType   string `json:"from_type"`
	ToType     string `json:"to_type"`
	Reversible bool   `json:"reversible"`
	DataLoss   bool   `json:"data_loss"`
}

TypeChange represents a type change in a migration

type TypeCompatibility

type TypeCompatibility struct {
	FromType           string             `json:"from_type"`
	ToType             string             `json:"to_type"`
	Compatible         bool               `json:"compatible"`
	RequiresCast       bool               `json:"requires_cast"`
	CastType           CastType           `json:"cast_type"`
	CompatibilityLevel CompatibilityLevel `json:"compatibility_level"`
	Warnings           []string           `json:"warnings"`
}

TypeCompatibility represents compatibility between types

type TypeConversion

type TypeConversion struct {
	FromType        string   `json:"from_type"`
	ToType          string   `json:"to_type"`
	ConversionSQL   string   `json:"conversion_sql"`
	Reversible      bool     `json:"reversible"`
	ReverseSQL      string   `json:"reverse_sql,omitempty"`
	DataLoss        bool     `json:"data_loss"`
	LossDescription string   `json:"loss_description,omitempty"`
	Warnings        []string `json:"warnings"`
}

TypeConversion represents a type conversion operation

type TypeDependency

type TypeDependency struct {
	DependentType string         `json:"dependent_type"`
	DependsOnType string         `json:"depends_on_type"`
	Relationship  DependencyType `json:"relationship"`
	Optional      bool           `json:"optional"`
}

TypeDependency represents a dependency relationship between types

type TypeInfo

type TypeInfo struct {
	Name         string           `json:"name"`
	Schema       string           `json:"schema"`
	Category     TypeCategory     `json:"category"`
	IsBuiltin    bool             `json:"is_builtin"`
	BaseType     string           `json:"base_type,omitempty"`
	Size         int              `json:"size"`
	Precision    int              `json:"precision,omitempty"`
	Scale        int              `json:"scale,omitempty"`
	Length       int              `json:"length,omitempty"`
	IsArray      bool             `json:"is_array"`
	ArrayDims    int              `json:"array_dims,omitempty"`
	ElementType  string           `json:"element_type,omitempty"`
	Modifiers    []string         `json:"modifiers"`
	Constraints  []string         `json:"constraints"`
	Dependencies []TypeDependency `json:"dependencies"`
	UsageContext []UsageContext   `json:"usage_context"`
}

TypeInfo contains comprehensive information about a database type

type UsageContext

type UsageContext struct {
	Location    string      `json:"location"`
	Context     ContextType `json:"context"`
	Required    bool        `json:"required"`
	Constraints []string    `json:"constraints"`
}

UsageContext tracks where and how a type is used

Jump to

Keyboard shortcuts

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