db

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BrokenIndexesRow

type BrokenIndexesRow struct {
	TableName string
	IndexName string
}

type ConnectionStatsRow

type ConnectionStatsRow struct {
	MaxConnections           pgtype.Int4
	ReservedConnections      pgtype.Int4
	TotalConnections         pgtype.Int8
	ActiveConnections        pgtype.Int8
	IdleConnections          pgtype.Int8
	IdleInTransaction        pgtype.Int8
	IdleInTransactionAborted pgtype.Int8
	WaitingConnections       pgtype.Int8
}

type DBTX

type DBTX interface {
	Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
	Query(context.Context, string, ...interface{}) (pgx.Rows, error)
	QueryRow(context.Context, string, ...interface{}) pgx.Row
}

type DatabaseCacheEfficiencyRow

type DatabaseCacheEfficiencyRow struct {
	BlksHit       pgtype.Int8
	BlksRead      pgtype.Int8
	StatsReset    pgtype.Timestamptz
	CacheHitRatio pgtype.Numeric
	StatsAgeDays  pgtype.Numeric
}

type DatabaseFreezeAgeRow

type DatabaseFreezeAgeRow struct {
	DatabaseName pgtype.Text
	FrozenXid    pgtype.Text
	FreezeAge    pgtype.Int4
	FreezeMaxAge pgtype.Int8
}

type DuplicateIndexesRow

type DuplicateIndexesRow struct {
	TableName     pgtype.Text
	IndexNameA    pgtype.Text
	IndexNameB    pgtype.Text
	SizeA         pgtype.Int8
	SizeB         pgtype.Int8
	DefinitionA   pgtype.Text
	DuplicateType pgtype.Text
}

type HighSeqScanTablesRow

type HighSeqScanTablesRow struct {
	TableName      pgtype.Text
	SeqScan        pgtype.Int8
	IdxScan        pgtype.Int8
	SeqToIdxRatio  pgtype.Numeric
	EstimatedRows  pgtype.Int8
	TableSizeBytes pgtype.Int8
	IndexCount     pgtype.Int8
}

type IdleInTransactionRow

type IdleInTransactionRow struct {
	Pid                        pgtype.Int4
	Username                   pgtype.Text
	DatabaseName               pgtype.Text
	ApplicationName            pgtype.Text
	State                      pgtype.Text
	TransactionDurationSeconds pgtype.Int8
	QueryPreview               pgtype.Text
	TimeoutMs                  pgtype.Int8
}

type IndexBloatRow

type IndexBloatRow struct {
	Schemaname   pgtype.Text
	Tablename    pgtype.Text
	Indexname    pgtype.Text
	ActualPages  int32
	EstPages     pgtype.Int8
	ActualBytes  pgtype.Int8
	BloatBytes   pgtype.Int8
	BloatPercent pgtype.Numeric
}

type IndexUsageStatsRow

type IndexUsageStatsRow struct {
	TableName      pgtype.Text
	IndexName      pgtype.Text
	NumRows        pgtype.Int8
	IsPrimary      bool
	IsUnique       bool
	IndexSizeBytes pgtype.Int8
	IdxScan        pgtype.Int8
	IdxTupRead     pgtype.Int8
	IdxTupFetch    pgtype.Int8
	TableWrites    pgtype.Int8
	IdxBlksHit     pgtype.Int8
	IdxBlksRead    pgtype.Int8
	CacheHitRatio  pgtype.Numeric
	Indexdef       pgtype.Text
}

type InvalidPrimaryKeyTypesRow

type InvalidPrimaryKeyTypesRow struct {
	TableName       pgtype.Text
	ColumnName      pgtype.Text
	ColumnType      pgtype.Text
	EstimatedRows   pgtype.Int8
	SequenceCurrent pgtype.Int8
	TypeMaxValue    pgtype.Int8
	UsagePct        pgtype.Numeric
}

type LargeTablesRow

type LargeTablesRow struct {
	TableName      pgtype.Text
	ParentTable    pgtype.Text
	TableSizeBytes pgtype.Int8
	EstimatedRows  pgtype.Int8
	IsPartitioned  pgtype.Bool
	IsPartition    pgtype.Bool
	IsTransient    pgtype.Bool
	NTupIns        pgtype.Int8
	NTupUpd        pgtype.Int8
	NTupDel        pgtype.Int8
}

type LongIdleConnectionsRow

type LongIdleConnectionsRow struct {
	Pid                  pgtype.Int4
	Username             pgtype.Text
	DatabaseName         pgtype.Text
	ApplicationName      pgtype.Text
	ClientAddress        pgtype.Text
	State                pgtype.Text
	IdleDurationSeconds  pgtype.Int8
	ConnectionAgeSeconds pgtype.Int8
}

type MissingProviderIdTablesRow

type MissingProviderIdTablesRow struct {
	DatabaseName   pgtype.Text
	TableName      pgtype.Text
	TableSizeBytes pgtype.Int8
	EstimatedRows  pgtype.Int8
}

type PGVersionRow

type PGVersionRow struct {
	Major int32
	Minor int32
}

type PartitionedTablesWithKeysRow

type PartitionedTablesWithKeysRow struct {
	SchemaName          pgtype.Text
	TableName           pgtype.Text
	PartitionStrategy   pgtype.Text
	PartitionKeyColumns pgtype.Text
	HasExpressionKey    pgtype.Bool
	PartitionCount      pgtype.Int8
	TotalSizeBytes      pgtype.Int8
	EstimatedRows       pgtype.Int8
	TotalSeqScans       pgtype.Int8
	TotalIdxScans       pgtype.Int8
}

type Queries

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

func New

func New(db DBTX) *Queries

func (*Queries) BrokenIndexes

func (q *Queries) BrokenIndexes(ctx context.Context) ([]BrokenIndexesRow, error)

func (*Queries) ConnectionStats

func (q *Queries) ConnectionStats(ctx context.Context) (ConnectionStatsRow, error)

Gets overall connection statistics including pool sizing metrics.

func (*Queries) DatabaseCacheEfficiency

func (q *Queries) DatabaseCacheEfficiency(ctx context.Context) (DatabaseCacheEfficiencyRow, error)

Returns database-wide buffer cache hit ratio. Low ratios indicate shared_buffers too small or working set exceeds memory.

func (*Queries) DatabaseFreezeAge

func (q *Queries) DatabaseFreezeAge(ctx context.Context) ([]DatabaseFreezeAgeRow, error)

Gets transaction ID age for all databases.

func (*Queries) DuplicateIndexes

func (q *Queries) DuplicateIndexes(ctx context.Context) ([]DuplicateIndexesRow, error)

Identifies exact and prefix duplicate indexes on the same table. Uses index column positions (indkey) for prefix detection. Excludes: system schemas, invalid indexes, expression/partial indexes for prefix check.

func (*Queries) HasPgStatStatements

func (q *Queries) HasPgStatStatements(ctx context.Context) (bool, error)

Checks if pg_stat_statements extension is installed.

func (*Queries) HighSeqScanTables

func (q *Queries) HighSeqScanTables(ctx context.Context) ([]HighSeqScanTablesRow, error)

Identifies tables with excessive sequential scans relative to index scans. Excludes: small tables, system schemas, tables with no indexes.

func (*Queries) IdleInTransaction

func (q *Queries) IdleInTransaction(ctx context.Context) ([]IdleInTransactionRow, error)

Identifies connections stuck in 'idle in transaction' state. Includes the timeout setting (in ms) for threshold calculation in Go.

func (*Queries) IndexBloat

func (q *Queries) IndexBloat(ctx context.Context) ([]IndexBloatRow, error)

Balanced B-tree index bloat estimation using pg_stats column widths Accuracy: ±15% (good enough for health checks, not precision measurement)

func (*Queries) IndexUsageStats

func (q *Queries) IndexUsageStats(ctx context.Context) ([]IndexUsageStatsRow, error)

Identifies indexes with usage statistics for health analysis. Excludes: system schemas. Returns data for subchecks: unused-indexes, low-usage-indexes, index-cache-ratio.

func (*Queries) InvalidPrimaryKeyTypes

func (q *Queries) InvalidPrimaryKeyTypes(ctx context.Context) ([]InvalidPrimaryKeyTypesRow, error)

Identifies tables with integer primary keys (int2/int4) that should use bigint.

func (*Queries) LargeTables

func (q *Queries) LargeTables(ctx context.Context) ([]LargeTablesRow, error)

Identifies all large tables (>= 10M rows) with partitioning and transient status. Returns both regular and partitioned tables for unified analysis. Includes activity metrics (inserts/updates/deletes) for activity-aware thresholds.

func (*Queries) LongIdleConnections

func (q *Queries) LongIdleConnections(ctx context.Context) ([]LongIdleConnectionsRow, error)

Identifies connections that have been idle for too long (potential pool leak).

func (*Queries) MissingProviderIdTables

func (q *Queries) MissingProviderIdTables(ctx context.Context) ([]MissingProviderIdTablesRow, error)

Identifies tables without provider_id column for multi-tenancy support.

func (*Queries) PGVersion

func (q *Queries) PGVersion(ctx context.Context) (PGVersionRow, error)

func (*Queries) PartitionedTablesWithKeys

func (q *Queries) PartitionedTablesWithKeys(ctx context.Context) ([]PartitionedTablesWithKeysRow, error)

Gets partitioned tables and their partition key column(s). Pre-aggregates all partition statistics in a single CTE for better performance compared to multiple correlated subqueries.

func (*Queries) QueryStatsFromStatStatements

func (q *Queries) QueryStatsFromStatStatements(ctx context.Context) ([]QueryStatsFromStatStatementsRow, error)

Gets query statistics from pg_stat_statements for partition key analysis. Returns queries with significant usage to check against partitioned tables.

func (*Queries) ReplicationLag

func (q *Queries) ReplicationLag(ctx context.Context) ([]ReplicationLagRow, error)

Monitors replication lag for both physical and logical replication streams. Joins with pg_replication_slots to get authoritative replication type and slot information.

func (*Queries) ReplicationSlots

func (q *Queries) ReplicationSlots(ctx context.Context) ([]ReplicationSlotsRow, error)

For PostgreSQL 17+: includes inactive_since, conflicting, invalidation_reason

func (*Queries) ReplicationSlotsPG15

func (q *Queries) ReplicationSlotsPG15(ctx context.Context) ([]ReplicationSlotsPG15Row, error)

For PostgreSQL 15/16: columns conflicting, invalidation_reason, inactive_since don't exist

func (*Queries) SequenceHealth

func (q *Queries) SequenceHealth(ctx context.Context) ([]SequenceHealthRow, error)

Identifies sequences approaching their maximum values and integer columns that should be bigint Find columns that own sequences (SERIAL/BIGSERIAL columns) Check if columns are primary keys Count foreign keys referencing each column (as the referenced/target column)

func (*Queries) SessionSettings

func (q *Queries) SessionSettings(ctx context.Context) ([]SessionSettingsRow, error)

func (*Queries) SessionStatistics

func (q *Queries) SessionStatistics(ctx context.Context) (SessionStatisticsRow, error)

Gets session time statistics from pg_stat_database (PostgreSQL 14+). These stats help analyze connection pool efficiency. Returns zero values for PostgreSQL versions < 14 (columns don't exist).

func (*Queries) StatisticsFreshness

func (q *Queries) StatisticsFreshness(ctx context.Context) (StatisticsFreshnessRow, error)

Returns statistics age for the current database. Use to validate stats are meaningful before relying on usage-based checks.

func (*Queries) TableActivity

func (q *Queries) TableActivity(ctx context.Context) ([]TableActivityRow, error)

Retrieves table write activity metrics from pg_stat_user_tables Used to identify high-churn tables and HOT update efficiency issues

func (*Queries) TableBloat

func (q *Queries) TableBloat(ctx context.Context) ([]TableBloatRow, error)

Identifies tables with high dead tuple percentages indicating vacuum issues

func (*Queries) TableFreezeAge

func (q *Queries) TableFreezeAge(ctx context.Context) ([]TableFreezeAgeRow, error)

Gets transaction ID age for tables with oldest frozen XIDs.

func (*Queries) TableVacuumHealth

func (q *Queries) TableVacuumHealth(ctx context.Context) ([]TableVacuumHealthRow, error)

Returns all tables with vacuum-related health metrics. Used by multiple subchecks: autovacuum-disabled, large-table-defaults, vacuum-stale, analyze-needed.

func (*Queries) TempUsage

func (q *Queries) TempUsage(ctx context.Context) (TempUsageRow, error)

Monitors temporary file creation indicating work_mem exhaustion

func (*Queries) ToastStorage

func (q *Queries) ToastStorage(ctx context.Context) ([]ToastStorageRow, error)

Analyzes TOAST storage usage and identifies tables with large value storage

func (*Queries) UuidColumnDefaults

func (q *Queries) UuidColumnDefaults(ctx context.Context) ([]UuidColumnDefaultsRow, error)

Find UUID columns with their DEFAULT expressions to detect random UUID usage.

func (*Queries) UuidColumnsAsString

func (q *Queries) UuidColumnsAsString(ctx context.Context) ([]UuidColumnsAsStringRow, error)

Identifies columns that appear to store UUIDs but use string types.

func (*Queries) VacuumSettings

func (q *Queries) VacuumSettings(ctx context.Context) ([]VacuumSettingsRow, error)

noqa: disable=RF04

func (*Queries) WithTx

func (q *Queries) WithTx(tx pgx.Tx) *Queries

type QueryStatsFromStatStatementsRow

type QueryStatsFromStatStatementsRow struct {
	QueryID       pgtype.Int8
	Query         pgtype.Text
	Calls         pgtype.Int8
	TotalExecTime pgtype.Float8
	MeanExecTime  pgtype.Float8
	RowsReturned  pgtype.Int8
}

type ReplicationLagRow

type ReplicationLagRow struct {
	ApplicationName  pgtype.Text
	State            pgtype.Text
	ReplicationType  pgtype.Text
	ReplayLagBytes   pgtype.Int8
	ReplayLagSeconds pgtype.Float8
	SlotName         pgtype.Text
	WalStatus        pgtype.Text
}

type ReplicationSlotsPG15Row

type ReplicationSlotsPG15Row struct {
	SlotName                  pgtype.Text
	SlotType                  pgtype.Text
	Plugin                    pgtype.Text
	Database                  pgtype.Text
	Active                    pgtype.Bool
	ActivePid                 pgtype.Int4
	WalStatus                 pgtype.Text
	SafeWalSize               pgtype.Int8
	Temporary                 pgtype.Bool
	Conflicting               pgtype.Bool
	InvalidationReason        pgtype.Text
	RestartLsnLagBytes        pgtype.Int8
	ConfirmedFlushLsnLagBytes pgtype.Int8
	InactiveSeconds           pgtype.Int8
}

type ReplicationSlotsRow

type ReplicationSlotsRow struct {
	SlotName                  pgtype.Text
	SlotType                  pgtype.Text
	Plugin                    pgtype.Text
	Database                  pgtype.Text
	Active                    pgtype.Bool
	ActivePid                 pgtype.Int4
	WalStatus                 pgtype.Text
	SafeWalSize               pgtype.Int8
	Temporary                 pgtype.Bool
	Conflicting               pgtype.Bool
	InvalidationReason        pgtype.Text
	RestartLsnLagBytes        pgtype.Int8
	ConfirmedFlushLsnLagBytes pgtype.Int8
	InactiveSeconds           pgtype.Int8
}

type SequenceHealthRow

type SequenceHealthRow struct {
	SchemaName            pgtype.Text
	SequenceName          pgtype.Text
	SeqDataType           pgtype.Text
	CurrentValue          pgtype.Int8
	MaxValue              pgtype.Int8
	IncrementBy           pgtype.Int8
	IsCyclic              pgtype.Bool
	RemainingValues       pgtype.Int8
	UsagePercent          pgtype.Numeric
	TableName             pgtype.Text
	ColumnName            pgtype.Text
	ColumnType            pgtype.Text
	ColumnMaxValue        pgtype.Int8
	SequenceExceedsColumn pgtype.Bool
	ShouldBeBigint        pgtype.Bool
	IsPrimaryKey          pgtype.Bool
	FkReferenceCount      pgtype.Int8
}

type SessionSettingsRow

type SessionSettingsRow struct {
	RoleName      pgtype.Text
	SettingName   pgtype.Text
	SystemDefault pgtype.Text
	Unit          pgtype.Text
	SettingValue  pgtype.Text
	Status        pgtype.Text
}

type SessionStatisticsRow

type SessionStatisticsRow struct {
	TotalSessionTimeMs      pgtype.Float8
	TotalActiveTimeMs       pgtype.Float8
	TotalIdleInTxnTimeMs    pgtype.Float8
	TotalSessions           pgtype.Int8
	SessionsAbandoned       pgtype.Int8
	SessionsFatal           pgtype.Int8
	SessionsKilled          pgtype.Int8
	SessionBusyRatioPercent pgtype.Float8
}

type StatisticsFreshnessRow

type StatisticsFreshnessRow struct {
	StatsReset  pgtype.Timestamptz
	AgeDays     pgtype.Int4
	AgeInterval pgtype.Interval
}

type TableActivityRow

type TableActivityRow struct {
	Schemaname     pgtype.Text
	Relname        pgtype.Text
	NTupIns        pgtype.Int8
	NTupUpd        pgtype.Int8
	NTupDel        pgtype.Int8
	NTupHotUpd     pgtype.Int8
	NLiveTup       pgtype.Int8
	TableSizeBytes pgtype.Int8
}

type TableBloatRow

type TableBloatRow struct {
	TableName                 pgtype.Text
	LiveTuples                pgtype.Int8
	DeadTuples                pgtype.Int8
	LastAutovacuum            pgtype.Timestamptz
	LastVacuum                pgtype.Timestamptz
	LastAutoanalyze           pgtype.Timestamptz
	LastAnalyze               pgtype.Timestamptz
	AutovacuumCount           pgtype.Int8
	VacuumCount               pgtype.Int8
	ModificationsSinceAnalyze pgtype.Int8
	DeadTuplePercent          pgtype.Numeric
	TotalSizeBytes            pgtype.Int8
}

type TableFreezeAgeRow

type TableFreezeAgeRow struct {
	TableName       pgtype.Text
	FrozenXid       pgtype.Text
	LastAutovacuum  pgtype.Timestamptz
	LastVacuum      pgtype.Timestamptz
	AutovacuumCount pgtype.Int8
	VacuumCount     pgtype.Int8
	FreezeAge       pgtype.Int4
	TableSizeBytes  pgtype.Int8
}

type TableVacuumHealthRow

type TableVacuumHealthRow struct {
	TableName        pgtype.Text
	LastAutovacuum   pgtype.Timestamptz
	EstimatedRows    pgtype.Int8
	TableSizeBytes   pgtype.Int8
	NDeadTup         pgtype.Int8
	AutovacuumCount  pgtype.Int8
	Reloptions       pgtype.Text
	LastVacuumAny    pgtype.Timestamptz
	LastAnalyzeAny   pgtype.Timestamptz
	NModSinceAnalyze pgtype.Int8
	AutoanalyzeCount pgtype.Int8
	NInsSinceVacuum  pgtype.Int8
}

type TempUsageRow

type TempUsageRow struct {
	DatabaseName      pgtype.Text
	TempFiles         pgtype.Int8
	TempBytes         pgtype.Int8
	StatsReset        pgtype.Timestamptz
	SecondsSinceReset pgtype.Numeric
	WorkMem           pgtype.Text
	TempFileLimit     pgtype.Text
	LogTempFiles      pgtype.Text
	MaxConnections    pgtype.Text
	SharedBuffers     pgtype.Text
	TempFilesPerHour  pgtype.Numeric
	TempBytesPerHour  pgtype.Numeric
}

type ToastStorageRow

type ToastStorageRow struct {
	SchemaName            pgtype.Text
	TableName             pgtype.Text
	ToastTableName        pgtype.Text
	MainTableSize         pgtype.Int8
	ToastSize             pgtype.Int8
	TotalSize             pgtype.Int8
	IndexesSize           pgtype.Int8
	ToastPercent          pgtype.Numeric
	ToastLiveTuples       pgtype.Int8
	ToastDeadTuples       pgtype.Int8
	WideColumns           []string
	ColumnCompressionInfo []string
}

type UuidColumnDefaultsRow

type UuidColumnDefaultsRow struct {
	TableName   pgtype.Text
	ColumnName  pgtype.Text
	DefaultExpr pgtype.Text
	HasIndex    pgtype.Bool
}

type UuidColumnsAsStringRow

type UuidColumnsAsStringRow struct {
	TableName      string
	ColumnName     string
	ColumnType     string
	TableSizeBytes int64
}

type VacuumSettingsRow

type VacuumSettingsRow struct {
	Name    pgtype.Text
	Setting pgtype.Text
	Unit    pgtype.Text
}

Jump to

Keyboard shortcuts

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