metadata

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package metadata provides database metadata extraction and management. It handles introspection of PostgreSQL databases, schema analysis, and metadata collection for migration squashing operations.

Package metadata provides schema comparison functionality

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsSystemFunction

func IsSystemFunction(funcName string, schemaName string) bool

IsSystemFunction checks if a function is a PostgreSQL system function

func IsSystemSchema

func IsSystemSchema(schemaName string) bool

IsSystemSchema checks if a schema is a PostgreSQL system schema

func IsSystemTable

func IsSystemTable(tableName string) bool

IsSystemTable checks if a table is a PostgreSQL system table

Types

type ColumnMetadata

type ColumnMetadata struct {
	Name               string `json:"name"`
	DataType           string `json:"data_type"`
	IsNullable         bool   `json:"is_nullable"`
	DefaultValue       string `json:"default_value,omitempty"`
	IsGenerated        bool   `json:"is_generated"`
	GenerationExpr     string `json:"generation_expr,omitempty"`
	IsIdentity         bool   `json:"is_identity"`
	IdentityGeneration string `json:"identity_generation,omitempty"`
	Collation          string `json:"collation,omitempty"`
	Comment            string `json:"comment,omitempty"`
}

ColumnMetadata represents detailed column information

type CompareOptions added in v1.2.0

type CompareOptions struct {
	// Schemas limits the comparison to these schemas; empty compares every
	// schema present in either model.
	Schemas []string
	// Environment describes what the scratch database already contained before
	// the baseline was applied (platform schemas, auth compatibility objects,
	// preinstalled extensions). Those objects are excluded from both sides.
	Environment *DatabaseMetadata
}

CompareOptions scopes a structural comparison.

type ComparisonResult

type ComparisonResult struct {
	IsValid             bool
	MissingExtensions   []string
	TypeMismatches      []TypeMismatch
	ConstraintConflicts []ConstraintConflict
	Warnings            []string
	SchemaDrift         []SchemaDrift
}

ComparisonResult is the outcome of a structural comparison between the expected schema (production) and the actual schema (the squashed baseline applied to an empty database). Both sides are DatabaseMetadata loaded by the same MetadataManager, so every definition was rendered by PostgreSQL itself.

IsValid is false when the baseline would not reproduce production inside the compared schemas: any object missing on either side, any column whose type, nullability, default, generation expression, identity or collation differs, a different column order, a different row-level-security flag, and any constraint, index, trigger, policy, view, materialized view, function (per identity signature), sequence, enum (labels in order) or other type whose definition differs. An extension the baseline creates but production does not have also invalidates the result, because the baseline could not be applied there.

Warnings never affect IsValid: an extension installed in production that the baseline does not create (managed platforms preinstall many), and an extension whose version differs.

func CompareDatabaseMetadata added in v1.2.0

func CompareDatabaseMetadata(expected, actual *DatabaseMetadata, opts CompareOptions) *ComparisonResult

CompareDatabaseMetadata compares expected (production) against actual (the generated baseline) and returns every difference in a deterministic order.

type ConstraintConflict

type ConstraintConflict struct {
	Table          string
	ConstraintName string
	ExpectedDef    string
	ActualDef      string
	ConflictType   string // "missing" (not in the baseline), "different", "extra" (not in production)
}

ConstraintConflict represents a constraint mismatch

type ConstraintMetadata

type ConstraintMetadata struct {
	Name              string   `json:"name"`
	Type              string   `json:"type"` // PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK
	Columns           []string `json:"columns"`
	RefTable          string   `json:"ref_table,omitempty"`
	RefColumns        []string `json:"ref_columns,omitempty"`
	OnDelete          string   `json:"on_delete,omitempty"`
	OnUpdate          string   `json:"on_update,omitempty"`
	CheckExpression   string   `json:"check_expression,omitempty"`
	IsDeferrable      bool     `json:"is_deferrable"`
	InitiallyDeferred bool     `json:"initially_deferred"`
	Definition        string   `json:"definition"` // pg_get_constraintdef
}

ConstraintMetadata represents table constraints

type DatabaseMetadata

type DatabaseMetadata struct {
	Database   string                        `json:"database"`
	Schemas    map[string]*SchemaMetadata    `json:"schemas"`
	SearchPath []string                      `json:"search_path"`
	Extensions map[string]*ExtensionMetadata `json:"extensions"`
	IsSystemDB bool                          `json:"is_system_db"`
	Version    *PostgreSQLVersion            `json:"version"`
	CreatedAt  time.Time                     `json:"created_at"`
}

DatabaseMetadata represents complete PostgreSQL database metadata

func (*DatabaseMetadata) AnalyzeViewDependencies

func (dbMeta *DatabaseMetadata) AnalyzeViewDependencies(view *ViewMetadata) ([]string, error)

AnalyzeViewDependencies extracts dependencies from view definitions

func (*DatabaseMetadata) GetSearchPath

func (dbMeta *DatabaseMetadata) GetSearchPath() []string

GetSearchPath returns the database search path with proper defaults

func (*DatabaseMetadata) SearchFunctions

func (dbMeta *DatabaseMetadata) SearchFunctions(searchPath []string, funcName string) ([]string, []*FunctionMetadata)

SearchFunctions searches for functions supporting overloading

func (*DatabaseMetadata) SearchObject

func (dbMeta *DatabaseMetadata) SearchObject(searchPath []string, objectName string) (schema, object string)

PostgreSQL-specific search path resolution

func (*DatabaseMetadata) SearchTable

func (dbMeta *DatabaseMetadata) SearchTable(searchPath []string, tableName string) (string, *TableMetadata)

SearchTable searches for a table in the search path

func (*DatabaseMetadata) SetSearchPath

func (dbMeta *DatabaseMetadata) SetSearchPath(path []string)

SetSearchPath sets the database search path with system path filtering

type ExtensionMetadata

type ExtensionMetadata struct {
	Name        string `json:"name"`
	Schema      string `json:"schema,omitempty"`
	Version     string `json:"version"`
	Comment     string `json:"comment,omitempty"`
	Relocatable bool   `json:"relocatable"`
}

ExtensionMetadata represents extension information

type FunctionMetadata

type FunctionMetadata struct {
	Name       string       `json:"name"`
	Schema     string       `json:"schema"`
	Signature  string       `json:"signature"`
	Language   string       `json:"language"`
	ReturnType string       `json:"return_type"`
	Parameters []*Parameter `json:"parameters"`
	Body       string       `json:"body"`
	Volatility string       `json:"volatility"` // VOLATILE, STABLE, IMMUTABLE
	IsStrict   bool         `json:"is_strict"`
	Security   string       `json:"security"` // DEFINER, INVOKER
	Comment    string       `json:"comment,omitempty"`
}

FunctionMetadata represents function information with overloading support

type IndexMetadata

type IndexMetadata struct {
	Name          string         `json:"name"`
	Schema        string         `json:"schema"`
	Table         string         `json:"table"`
	Columns       []string       `json:"columns"`
	Expressions   []string       `json:"expressions,omitempty"`
	Method        string         `json:"method"` // BTREE, HASH, GIN, GIST, etc.
	IsUnique      bool           `json:"is_unique"`
	IsPrimary     bool           `json:"is_primary"`
	IsPartial     bool           `json:"is_partial"`
	WhereClause   string         `json:"where_clause,omitempty"`
	Definition    string         `json:"definition"`
	TableMetadata *TableMetadata `json:"-"` // Back-reference
}

IndexMetadata represents index information with parent table references

type MaterializedViewMetadata

type MaterializedViewMetadata struct {
	*ViewMetadata
	HasData    bool     `json:"has_data"`
	Indexes    []string `json:"indexes"`
	Tablespace string   `json:"tablespace,omitempty"`
}

MaterializedViewMetadata represents materialized view information

type MetadataManager

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

MetadataManager provides comprehensive PostgreSQL metadata management with lazy-loading, caching, and search path resolution

func NewMetadataManager

func NewMetadataManager(db *sql.DB, cacheTTL time.Duration) *MetadataManager

NewMetadataManager creates a new metadata manager

func (*MetadataManager) GetCacheStats

func (m *MetadataManager) GetCacheStats() (hits, misses int64, ratio float64)

GetCacheStats returns cache performance statistics

func (*MetadataManager) GetMetadata

func (m *MetadataManager) GetMetadata(ctx context.Context, database string) (*DatabaseMetadata, error)

GetMetadata retrieves database metadata with caching

func (*MetadataManager) InvalidateMetadata

func (m *MetadataManager) InvalidateMetadata(database string)

InvalidateMetadata removes cached metadata

type Parameter

type Parameter struct {
	Name    string `json:"name"`
	Type    string `json:"type"`
	Mode    string `json:"mode"` // IN, OUT, INOUT
	Default string `json:"default,omitempty"`
}

Parameter represents function parameter

type PolicyMetadata

type PolicyMetadata struct {
	Name       string   `json:"name"`
	Table      string   `json:"table"`
	Schema     string   `json:"schema"`
	Command    string   `json:"command"`    // ALL, SELECT, INSERT, UPDATE, DELETE
	Permissive bool     `json:"permissive"` // PERMISSIVE or RESTRICTIVE
	Roles      []string `json:"roles"`
	Using      string   `json:"using,omitempty"`
	WithCheck  string   `json:"with_check,omitempty"`
}

PolicyMetadata represents RLS policy information

type PostgreSQLVersion

type PostgreSQLVersion struct {
	Major    int             `json:"major"`
	Minor    int             `json:"minor"`
	Patch    int             `json:"patch"`
	Features map[string]bool `json:"features"`
}

PostgreSQLVersion represents PostgreSQL version information

type SchemaDrift

type SchemaDrift struct {
	Object      string
	ObjectType  string
	Description string
	DriftType   string // "missing_in_db" (baseline only), "extra_in_db" (production only), "definition_mismatch"
}

SchemaDrift represents drift between the squashed baseline and production

type SchemaMetadata

type SchemaMetadata struct {
	Name              string                               `json:"name"`
	Tables            map[string]*TableMetadata            `json:"tables"`
	Views             map[string]*ViewMetadata             `json:"views"`
	MaterializedViews map[string]*MaterializedViewMetadata `json:"materialized_views"`
	Functions         map[string][]*FunctionMetadata       `json:"functions"` // Support overloading
	Sequences         map[string]*SequenceMetadata         `json:"sequences"`
	Types             map[string]*TypeMetadata             `json:"types"`
	Indexes           map[string]*IndexMetadata            `json:"indexes"`
	IsSystem          bool                                 `json:"is_system"`
}

SchemaMetadata represents a PostgreSQL schema with all its objects

type SequenceMetadata

type SequenceMetadata struct {
	Name      string `json:"name"`
	Schema    string `json:"schema"`
	DataType  string `json:"data_type"`
	Start     int64  `json:"start"`
	Increment int64  `json:"increment"`
	MinValue  int64  `json:"min_value"`
	MaxValue  int64  `json:"max_value"`
	Cache     int64  `json:"cache"`
	Cycle     bool   `json:"cycle"`
	OwnedBy   string `json:"owned_by,omitempty"`
}

SequenceMetadata represents sequence information

type TableMetadata

type TableMetadata struct {
	Name        string                `json:"name"`
	Schema      string                `json:"schema"`
	Columns     []*ColumnMetadata     `json:"columns"`
	Constraints []*ConstraintMetadata `json:"constraints"`
	Indexes     []*IndexMetadata      `json:"indexes"`
	Triggers    []*TriggerMetadata    `json:"triggers"`
	Policies    []*PolicyMetadata     `json:"policies"`
	Comment     string                `json:"comment,omitempty"`
	Tablespace  string                `json:"tablespace,omitempty"`
	RowSecurity bool                  `json:"row_security"`
}

TableMetadata represents comprehensive table information

type TriggerMetadata

type TriggerMetadata struct {
	Name       string   `json:"name"`
	Table      string   `json:"table"`
	Schema     string   `json:"schema"`
	Function   string   `json:"function"`
	Events     []string `json:"events"` // INSERT, UPDATE, DELETE
	Timing     string   `json:"timing"` // BEFORE, AFTER, INSTEAD OF
	Level      string   `json:"level"`  // ROW, STATEMENT
	Condition  string   `json:"condition,omitempty"`
	IsEnabled  bool     `json:"is_enabled"`
	Definition string   `json:"definition"` // pg_get_triggerdef
}

TriggerMetadata represents trigger information

type TypeMetadata

type TypeMetadata struct {
	Name       string   `json:"name"`
	Schema     string   `json:"schema"`
	Type       string   `json:"type"` // ENUM, COMPOSITE, DOMAIN, RANGE
	Definition string   `json:"definition"`
	Elements   []string `json:"elements,omitempty"` // For ENUM types
	Comment    string   `json:"comment,omitempty"`
}

TypeMetadata represents custom type information

type TypeMismatch

type TypeMismatch struct {
	Object       string
	Column       string
	ExpectedType string
	ActualType   string
	IsBreaking   bool
}

TypeMismatch represents a column whose data type differs.

type ViewMetadata

type ViewMetadata struct {
	Name         string   `json:"name"`
	Schema       string   `json:"schema"`
	Definition   string   `json:"definition"`
	Dependencies []string `json:"dependencies"`
	Comment      string   `json:"comment,omitempty"`
}

ViewMetadata represents view information

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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