db

package
v0.4.0 Latest Latest
Warning

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

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

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

Documentation

Overview

Package db implements PostgreSQL-only connections, planning-context identity, catalog metadata, statistics, and caches.

Index

Constants

This section is empty.

Variables

View Source
var ErrMetadataCacheClosed = errors.New("PostgreSQL metadata cache is closed")

ErrMetadataCacheClosed prevents reuse after the cache's lifecycle has ended.

Functions

func ComparePlanningIdentities

func ComparePlanningIdentities(expected, actual PlanningIdentity) error

ComparePlanningIdentities rejects cross-context result composition.

func NotInSubqueryOutputNotNull

func NotInSubqueryOutputNotNull(bound *parser.BoundStatement, condition parser.Condition, relations []*Relation) bool

NotInSubqueryOutputNotNull proves each output non-null using syntax evidence or bound physical relation identities and attnotnull catalog snapshots. Direct CTE projections can retain that proof. Missing/ambiguous identities, outer-scope outputs and null-extending shapes are unproven. Statistics are never non-null evidence. This function does not query or mutate the catalog.

func SnapshotDigest

func SnapshotDigest(relations []*Relation) string

SnapshotDigest returns a stable catalog/statistics fingerprint.

Types

type CollectionError

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

CollectionError retains completed structure when a later catalog operation fails. It never represents a complete metadata snapshot and is not cacheable.

func (*CollectionError) BaseRelations

func (e *CollectionError) BaseRelations() []*Relation

BaseRelations returns independent copies of completed relation, column and index facts. Statistics, partitions and publications are intentionally absent.

func (*CollectionError) Error

func (e *CollectionError) Error() string

Error excludes raw server details from the public error text.

func (*CollectionError) Unwrap

func (e *CollectionError) Unwrap() error

Unwrap preserves the server or context error for typed classification.

type Collector

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

Collector batches PostgreSQL catalog reads by relation OID.

func NewCollector

func NewCollector(database *sql.DB) *Collector

NewCollector constructs a catalog collector.

func (*Collector) Collect

func (collector *Collector) Collect(ctx context.Context, relationOIDs []uint32, level MetadataLevel) ([]*Relation, error)

Collect reads PostgreSQL catalog facts without reading user table data.

type Column

type Column struct {
	AttributeNumber   int16
	Name              string
	TypeOID           uint32
	TypeName          string
	TypeModifier      int32
	Nullable          bool
	CollationOID      uint32
	CollationName     string
	StatisticsTarget  int32
	Identity          string `json:",omitempty"`
	Generated         string `json:",omitempty"`
	DefaultExpression string `json:",omitempty"`
	SequenceBacked    bool   `json:",omitempty"`
}

Column is a PostgreSQL attribute snapshot.

type ColumnStatistics

type ColumnStatistics struct {
	Column              string
	Inherited           bool
	NullFraction        float64
	AverageWidth        int32
	NDistinct           float64
	MostCommonValues    []string
	MostCommonFreqs     []float64
	HistogramBounds     []string
	Correlation         float64
	HasMostCommonValues bool
	HasHistogram        bool
	HasCorrelation      bool
}

ColumnStatistics is a pg_stats snapshot. JSON values retain PostgreSQL's textual representation without persisting sampled table rows.

type ConnectionConfig

type ConnectionConfig struct {
	SearchPath []string
}

ConnectionConfig fixes session state that can alter PostgreSQL planning.

type DDLCatalog

type DDLCatalog struct {
	Relations   map[int]*DDLRelation
	TargetTypes map[string]DDLType
	BinaryCasts map[[2]uint32]bool
}

DDLCatalog contains nullable relation lookups. Missing request ordinals mean that no table-like object was visible under the captured search path.

func CollectDDLCatalog

func CollectDDLCatalog(ctx context.Context, database *sql.DB, requests []DDLRelationRequest, targetTypes []string) (*DDLCatalog, error)

CollectDDLCatalog resolves visible table-like objects without requiring every request to exist, then reads only pg_catalog. It never executes supplied DDL.

func (*DDLCatalog) Relation

func (catalog *DDLCatalog) Relation(ordinal int) *DDLRelation

Relation returns the catalog relation resolved for one request ordinal.

type DDLColumn

type DDLColumn struct {
	AttributeNumber int16
	Name            string
	TypeOID         uint32
	TypeName        string
	TypeModifier    int32
	// NotNull is pg_attribute.attnotnull for supported PG16/17 profiles.
	NotNull          bool
	DependentObjects int64
	Dependencies     []string
}

DDLColumn is catalog evidence for a live user column.

type DDLConstraint

type DDLConstraint struct {
	OID     uint32
	Name    string
	Kind    string
	Columns []string
	// BackingIndex is populated only for PRIMARY KEY, UNIQUE, and EXCLUSION
	// constraints. A foreign key's conindid identifies a referenced index and
	// is deliberately excluded.
	BackingIndex     string
	DependentObjects int64
	// Dependencies contains at most five descriptions from the address-deduped
	// direct dependency set; DependentObjects retains the complete count.
	Dependencies []string
}

DDLConstraint is catalog evidence for a table constraint.

type DDLRelation

type DDLRelation struct {
	RequestOrdinal   int
	OID              uint32
	Schema           string
	Name             string
	Kind             string
	Persistence      string
	Tuples           float64
	DependentObjects int64
	Dependencies     []string
	Columns          []DDLColumn
	Constraints      []DDLConstraint
	Partitions       []Partition
	// PartitionKeyColumns is set only when every partition key is a plain column.
	PartitionKeyColumns []string
	// PartitionKeyHasExpression is true when any partition key is an expression.
	PartitionKeyHasExpression bool
	// RowSecurityPolicies is the number of pg_policy rows visible for the relation.
	RowSecurityPolicies int
}

DDLRelation is a request-local catalog snapshot used only to qualify destructive DDL diagnostics.

type DDLRelationRequest

type DDLRelationRequest struct {
	Ordinal int    `json:"ordinal"`
	Schema  string `json:"schema_name"`
	Name    string `json:"relation_name"`
}

DDLRelationRequest is one source relation reference used by the destructive DDL analyzer. Ordinal is request-local and need not be a SQL byte offset.

type DDLType

type DDLType struct {
	OID  uint32
	Name string
}

DDLType identifies a target type resolved under the connected session.

type ExtendedStatistics

type ExtendedStatistics struct {
	Name                      string
	Columns                   []string
	Kinds                     []string
	Definition                string
	NDistinct                 string
	Dependencies              string
	MostCommonValues          string
	MostCommonFrequencies     []float64
	MostCommonBaseFrequencies []float64
}

ExtendedStatistics is one pg_statistic_ext definition summary.

type Index

type Index struct {
	OID              uint32
	Name             string
	AccessMethod     string
	Pages            int64   `json:"Pages,omitempty"`
	Tuples           float64 `json:"Tuples,omitempty"`
	Unique           bool
	Primary          bool
	Valid            bool
	Ready            bool
	Live             bool
	Clustered        bool
	NullsNotDistinct bool
	KeyColumns       []string
	IncludeColumns   []string
	Directions       []string
	NullOrdering     []string
	OperatorClasses  []string
	Collations       []string
	// OperatorClassBuiltinDefault proves each search key uses the pg_catalog
	// default opclass for its attribute type and this index's access method.
	OperatorClassBuiltinDefault []bool `json:",omitempty"`
	// CollationOIDs preserves exact key collation identities; names alone can
	// collide across schemas. Noncollatable keys have OID zero.
	CollationOIDs []uint32 `json:",omitempty"`
	// UniqueImmediate excludes deferrable uniqueness from row-uniqueness proofs.
	UniqueImmediate bool `json:",omitempty"`
	Expression      string
	Predicate       string
}

Index is a PostgreSQL access-method index snapshot.

type MetadataCache

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

MetadataCache stores immutable catalog snapshots with bounded LRU retention and coalesces identical loader requests without sharing caller data.

func NewMetadataCache

func NewMetadataCache() *MetadataCache

NewMetadataCache constructs bounded storage without a background goroutine. Use NewMetadataCacheWithConfig to opt into periodic expired-entry cleanup.

func NewMetadataCacheWithConfig

func NewMetadataCacheWithConfig(config *MetadataCacheConfig) *MetadataCache

NewMetadataCacheWithConfig freezes the supplied policy; nil uses defaults. Close stops its optional sweeper and prevents delayed loader publication.

func (*MetadataCache) Clear

func (c *MetadataCache) Clear()

Clear removes entries and prevents in-flight loads from repopulating them.

func (*MetadataCache) Close

func (c *MetadataCache) Close()

Close releases retained data and stops the optional sweeper. It is idempotent. Active caller-owned loaders may finish but cannot publish after Close.

func (*MetadataCache) Get

func (c *MetadataCache) Get(key MetadataCacheKey) (*Relation, bool)

Get returns an isolated catalog snapshot.

func (*MetadataCache) Invalidate

func (c *MetadataCache) Invalidate(oid uint32)

Invalidate removes relation entries and ancestors containing that partition.

func (*MetadataCache) InvalidateName

func (c *MetadataCache) InvalidateName(schema, table string)

InvalidateName removes all contexts/levels for a name and its ancestors.

func (*MetadataCache) Load

func (c *MetadataCache) Load(ctx context.Context, key MetadataCacheKey, loader func(context.Context) (*Relation, error)) (*Relation, error)

Load coalesces same-key loads. Followers cancel independently; the leader runs synchronously so its connection remains owned until its loader exits. Errors and results invalidated during loading are never cached.

func (*MetadataCache) LoadMany

func (c *MetadataCache) LoadMany(ctx context.Context, identity PlanningIdentity, level MetadataLevel, oids []uint32, loader func(context.Context, []uint32) ([]*Relation, error)) ([]*Relation, error)

LoadMany reads cache hits and calls loader once for the sorted, distinct missing OIDs. Results retain the input's first-occurrence order and never share mutable storage. Identical miss sets coalesce within a cache generation; invalidation prevents both joining and publishing an obsolete batch.

func (*MetadataCache) Put

func (c *MetadataCache) Put(key MetadataCacheKey, relation *Relation)

Put stores a replacement catalog snapshot.

type MetadataCacheConfig

type MetadataCacheConfig struct {
	BaseTTL        time.Duration
	MaxBaseEntries int
	SweepInterval  time.Duration
}

MetadataCacheConfig defines catalog retention. Explicit nonpositive capacities disable storage; TTLs are never defaulted.

func DefaultMetadataCacheConfig

func DefaultMetadataCacheConfig() *MetadataCacheConfig

DefaultMetadataCacheConfig returns an independent bounded retention policy.

type MetadataCacheKey

type MetadataCacheKey struct {
	Identity    PlanningIdentity
	Level       MetadataLevel
	RelationOID uint32
}

MetadataCacheKey prevents hits across PostgreSQL planning contexts.

type MetadataLevel

type MetadataLevel string

MetadataLevel selects PostgreSQL catalog depth without sampling user data.

const (
	// MetadataBase reads relation, column, index, and partition facts.
	MetadataBase MetadataLevel = "BASE"
	// MetadataStats additionally reads pg_stats and extended statistics.
	MetadataStats MetadataLevel = "STATS"
)

type NamespaceIdentity

type NamespaceIdentity struct {
	OID  uint32
	Name string
}

NamespaceIdentity is one effective search_path namespace in lookup order.

type Partition

type Partition struct {
	RelationOID   uint32 `json:",omitempty"`
	Schema        string `json:",omitempty"`
	Name          string `json:",omitempty"`
	ParentOID     uint32
	Strategy      string
	KeyDefinition string
	Bound         string
}

Partition describes parentage, key, and bound text from pg_catalog.

type PlannerSetting

type PlannerSetting struct {
	Name    string
	Setting string
	Unit    string
}

PlannerSetting is one explicitly captured setting consumed by analysis.

type PlanningContext

type PlanningContext struct {
	ServerVersionNum int
	ServerVersion    string
	DatabaseOID      uint32
	EffectiveRoleOID uint32
	RawSearchPath    string
	SearchPath       []NamespaceIdentity
	RowSecurity      string
	PlannerSettings  []PlannerSetting
}

PlanningContext is the captured PostgreSQL identity for one connected stage.

func CapturePlanningContext

func CapturePlanningContext(ctx context.Context, queryer contextQueryer) (PlanningContext, error)

CapturePlanningContext reads server, database, role, search_path, RLS, and planner setting identity using only pg_catalog/current_setting.

func (PlanningContext) Identity

func (planning PlanningContext) Identity(profile, snapshotDigest string) PlanningIdentity

Identity returns a stable digest-based identity. Planner settings are sorted on a copy so caller-owned order and data are not mutated.

type PlanningContextMismatchError

type PlanningContextMismatchError struct {
	Field string
}

PlanningContextMismatchError identifies the first non-comparable field.

func (*PlanningContextMismatchError) Error

Error implements error.

type PlanningIdentity

type PlanningIdentity struct {
	Profile               string
	ServerVersionNum      int
	DatabaseOID           uint32
	EffectiveRoleOID      uint32
	SearchPathDigest      string
	RLSContextDigest      string
	PlannerSettingsDigest string
	SnapshotDigest        string
}

PlanningIdentity is the comparable and cacheable context summary.

type Publication

type Publication struct {
	Name   string
	Update bool
	Delete bool
}

Publication is a pg_publication snapshot that includes a relation.

type Relation

type Relation struct {
	OID             uint32
	NamespaceOID    uint32
	Schema          string
	Name            string
	Kind            string
	Pages           int64
	Tuples          float64
	AllVisiblePages int64
	// HasSubclasses is pg_class.relhassubclass; parent indexes do not constrain
	// traditional inheritance descendants scanned without ONLY.
	HasSubclasses         bool `json:",omitempty"`
	Columns               []Column
	Indexes               []Index
	Statistics            []ColumnStatistics
	ExtendedStatistics    []ExtendedStatistics
	Partitions            []Partition
	PartitionInventory    []Partition `json:",omitempty"`
	StatisticsMaintenance StatisticsMaintenance
	// ReplicaIdentity is pg_class.relreplident: d, n, f, or i.
	ReplicaIdentity string `json:",omitempty"`
	// Publications lists publications that include this relation.
	Publications []Publication `json:",omitempty"`
}

Relation is an immutable-after-construction PostgreSQL relation snapshot.

type RelationRequest

type RelationRequest struct {
	Position int    `json:"position"`
	Schema   string `json:"schema_name"`
	Name     string `json:"relation_name"`
}

RelationRequest is a source-positioned relation name for batch OID lookup.

type ResolvedRelation

type ResolvedRelation struct {
	Position     int
	OID          uint32
	NamespaceOID uint32
	Schema       string
	Name         string
}

ResolvedRelation is the effective PostgreSQL catalog identity.

func ResolveRelationOIDs

func ResolveRelationOIDs(ctx context.Context, database *sql.DB, requests []RelationRequest) ([]ResolvedRelation, error)

ResolveRelationOIDs resolves explicit schemas and unqualified names in current_schemas(true) order with one pg_catalog query.

type SpecialIndexCapabilities

type SpecialIndexCapabilities struct {
	LowerImmutable          bool
	LowerVisible            bool
	DeterministicCollations []uint32
	TrigramOpclasses        []TrigramOpclass
}

SpecialIndexCapabilities contains request-local catalog proof. It is not cached: extension installation, function visibility and collation state can change independently of relation snapshots. An absent proof grants nothing.

func CollectSpecialIndexCapabilities

func CollectSpecialIndexCapabilities(ctx context.Context, database *sql.DB, oids []uint32) (*SpecialIndexCapabilities, error)

CollectSpecialIndexCapabilities performs one read-only catalog round trip. Call only when parsed expression or trigram candidates need these proofs.

type StatisticsMaintenance

type StatisticsMaintenance struct {
	LastAnalyze               time.Time
	LastAutoAnalyze           time.Time
	ModificationsSinceAnalyze int64
	LiveTuples                int64
	DefaultStatisticsTarget   int32
	AnalyzeThreshold          float64
	AutoAnalyzeEnabled        bool
	ChildStatisticsChanged    bool
}

StatisticsMaintenance retains catalog-only signals used to diagnose missing or stale planner statistics. Times are zero when PostgreSQL has not recorded the corresponding manual or automatic ANALYZE.

type StatisticsPermissionError

type StatisticsPermissionError struct {
	OID      uint32
	Schema   string
	Relation string
}

StatisticsPermissionError reports that pg_stats intentionally hides a relation from the effective role.

func (*StatisticsPermissionError) Error

func (e *StatisticsPermissionError) Error() string

Error implements error without exposing driver or connection details.

type Store

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

Store owns the PostgreSQL database/sql pool and its homogeneous session initialization policy.

func Open

func Open(ctx context.Context, dsn string, config ConnectionConfig) (*Store, error)

Open creates a pgx/v5 database/sql pool with after-connect and reset hooks.

func (*Store) Close

func (store *Store) Close() error

Close releases the connection pool.

func (*Store) PlanningContext

func (store *Store) PlanningContext(ctx context.Context) (PlanningContext, error)

PlanningContext captures the current homogeneous pool context.

func (*Store) SQLDB

func (store *Store) SQLDB() *sql.DB

SQLDB returns the PostgreSQL-owned pool to sibling PostgreSQL packages. It must not be exposed through the public analysis DTO.

type TrigramOpclass

type TrigramOpclass struct {
	Schema string
	Name   string
	Method string
}

TrigramOpclass is an accessible, extension-owned text operator class.

Jump to

Keyboard shortcuts

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