pg

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const ActiveConnectionsQuery = `
SELECT COUNT(*) AS active_connections
FROM pg_stat_activity
WHERE state = 'active'
`
View Source
const AlterDatabaseQuery = `
ALTER DATABASE %s SET %s = %s;
`
View Source
const AlterSystemQuery = `
ALTER SYSTEM SET %s = %s;
`
View Source
const AutovacuumQuery = `
SELECT COUNT(*) FROM pg_stat_activity WHERE starts_with(query, 'autovacuum:');
`

https://stackoverflow.com/a/25012622

View Source
const CheckPGStatStatementsQuery = `
SELECT COUNT(*) FROM pg_stat_statements;
`
View Source
const (
	DEFAULT_CONFIG_KEY = "postgresql"
)
View Source
const DataDirectoryQuery = `
SHOW data_directory;
`
View Source
const DatabaseSizeQuery = `
SELECT sum(pg_database_size(datname)) as total_size_bytes FROM pg_database;
`
View Source
const MaxConnectionsQuery = `
SELECT setting::integer FROM pg_settings WHERE  name = 'max_connections';
`
View Source
const PGStatBGWriterQuery = `
SELECT
    buffers_clean,
	maxwritten_clean,
	buffers_alloc
FROM pg_stat_bgwriter;
`
View Source
const PGStatCheckpointerQuery = `
SELECT
    num_timed,
	num_requested,
	write_time,
	sync_time,
	buffers_written
FROM pg_stat_checkpointer
`
View Source
const PGStatDatabaseQuery = `` /* 258-byte string literal not displayed */
View Source
const PGStatUserTablesQuery = `` /* 596-byte string literal not displayed */
View Source
const PGStatWalQuery = `
SELECT
    wal_records,
	wal_fpi,
	wal_bytes,
	wal_buffers_full
FROM pg_stat_wal;
`
View Source
const PGVersionQuery = `
SELECT version();
`

PGVersion returns the version of the PostgreSQL instance

View Source
const ReloadConfigQuery = `
SELECT pg_reload_conf();
`
View Source
const SELECT_NON_NUMERIC_SETTINGS = `
	SELECT name, setting, unit, vartype, context
	FROM pg_settings
	WHERE vartype NOT IN ('real', 'integer');
`
View Source
const SELECT_NUMERIC_SETTINGS = `
	SELECT name, setting::numeric as setting, unit, vartype, context
	FROM pg_settings
	WHERE vartype IN ('real', 'integer');
`
View Source
const Select1Query = `
SELECT 1;
`
View Source
const TransactionsPerSecondQuery = `
SELECT SUM(xact_commit)::bigint
AS server_xact_commits
FROM pg_stat_database;
`
View Source
const UptimeMinutesQuery = `
SELECT EXTRACT(EPOCH FROM (current_timestamp - pg_postmaster_start_time())) / 60 as uptime_minutes;
`
View Source
const WaitEventsQuery = `` /* 674-byte string literal not displayed */

Variables

View Source
var PgStatStatementsQueryBase = fmt.Sprintf(`
SELECT
	queryid,
	userid,
	dbid,
	calls,
	total_exec_time,
	rows
FROM pg_stat_statements
WHERE NOT starts_with(query, '%s')
  AND query !~* '^\\s*(BEGIN|COMMIT|ROLLBACK|SET |SHOW |SELECT (pg_|\\$1$|version\\s*\\(\\s*\\)))\\s*;?\\s*$'
`, utils.DBtuneQueryPrefix)

PgStatStatementsQueryBase queries pg_stat_statements excluding system queries. Filters out: dbtune queries (using fast starts_with), transactions (BEGIN/COMMIT/ROLLBACK), pg_* system queries, parameterized health checks (SELECT $1), version checks, SET/SHOW statements

View Source
var PgStatStatementsQueryWithTextFmt = fmt.Sprintf(`
SELECT
	queryid,
	userid,
	dbid,
	calls,
	total_exec_time,
	rows,
	LEFT(query, %%d) as query
FROM pg_stat_statements
WHERE NOT starts_with(query, '%s')
  AND query !~* '^\\s*(BEGIN|COMMIT|ROLLBACK|SET |SHOW |SELECT (pg_|\\$1$|version\\s*\\(\\s*\\)))\\s*;?\\s*$'
`, utils.DBtuneQueryPrefix)

PgStatStatementsQueryWithTextFmt is like PgStatStatementsQueryBase but includes query text. The first %s is replaced with the dbtune prefix (/*dbtune*/) The %%d is a format placeholder for the maximum query text length (filled in at runtime)

Functions

func ActiveConnections

func ActiveConnections(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

func AlterDatabase

func AlterDatabase(pgPool *pgxpool.Pool, dbname string, name string, value string) error

func AlterSystem

func AlterSystem(pgPool *pgxpool.Pool, name string, value string) error

func Autovacuum

func Autovacuum(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

func CheckPGStatStatements added in v0.4.0

func CheckPGStatStatements(pgPool *pgxpool.Pool) error

func DataDirectory

func DataDirectory(pgPool *pgxpool.Pool) (string, error)

func DatabaseSize

func DatabaseSize(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

DatabaseSize returns the size of all the databases combined in bytes

func DetectConfigFromConfigFile

func DetectConfigFromConfigFile() bool

func DetectConfigFromEnv

func DetectConfigFromEnv() bool

func EmitCumulativeMetricsMap added in v0.4.0

func EmitCumulativeMetricsMap[T Number](state *agent.MetricsState, mappings []MetricMapping[T]) error

Helper function to calculate the delta and emit a number of cumulative metrics The mapping takes the current value, the previous value and the metric to emit If either current or previous is nil, the metric is skipped

Note that cumulative metrics should be positive and monotonically increasing

In some cases, the delta can be negative (e.g. if the counter has been reset) In those cases, the metric is also skipped

func EmitMetric added in v0.4.0

func EmitMetric(state *agent.MetricsState, metric metrics.MetricDef, value any) error

Helper function reformat and emit a single metric

func GetActiveConfig

func GetActiveConfig(
	pool *pgxpool.Pool,
	ctx context.Context,
	logger *logrus.Logger,
) (agent.ConfigArraySchema, error)

func MaxConnections

func MaxConnections(pgPool *pgxpool.Pool) (uint32, error)

func PGStatBGwriter added in v0.4.0

func PGStatBGwriter(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

PGStatBGwriter collects statistics from pg_stat_bgwriter and computes and emits deltas for them.

func PGStatCheckpointer added in v0.4.0

func PGStatCheckpointer(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

PG stat database has info about IO, temp files and idle temp time. Many of those are cumulative metrics and require

func PGStatDatabase added in v0.4.0

func PGStatDatabase(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

PG stat database has info about IO, temp files and idle transaction time. Many of those are cumulative metrics and require calculating deltas between collection intervals. This function fetches and emits a number of those as well as calaculates the pg_cache_hit_ratio which is a derivative from blks_read and blks_hit

func PGStatStatements

func PGStatStatements(pgPool *pgxpool.Pool, includeQueries bool, maxQueryTextLength int) func(ctx context.Context, state *agent.MetricsState) error

func PGStatUserTables added in v0.4.0

func PGStatUserTables(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

PGStatUserTables collects statistics from pg_stat_user_tables, computes deltas for various metrics per table, and emits them as metrics for monitoring purposes. It tracks metrics such as autovacuum counts, live/dead tuples, and sequential/index scans, providing insights into table activity and performance over time.

func PGStatWAL added in v0.4.0

func PGStatWAL(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

PGStatWAL collects statistics from pg_stat_wal and computes and emits deltas for them.

func PGVersion

func PGVersion(pgPool *pgxpool.Pool) (string, error)

Example: 16.4

func ReloadConfig

func ReloadConfig(pgPool *pgxpool.Pool) error

func Select1

func Select1(pgPool *pgxpool.Pool) error

func TransactionsPerSecond

func TransactionsPerSecond(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

func UptimeMinutes added in v0.3.3

func UptimeMinutes(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

func WaitEvents

func WaitEvents(pgPool *pgxpool.Pool) func(ctx context.Context, state *agent.MetricsState) error

func WaitPostgresReady

func WaitPostgresReady(pgPool *pgxpool.Pool) error

Types

type Config

type Config struct {
	ConnectionURL          string `mapstructure:"connection_url" validate:"required"`
	ServiceName            string `mapstructure:"service_name"`
	IncludeQueries         bool   `mapstructure:"include_queries"`
	MaximumQueryTextLength int    `mapstructure:"maximum_query_text_length"`
}

func ConfigFromViper

func ConfigFromViper(key *string) (Config, error)

type MetricMapping added in v0.4.0

type MetricMapping[T Number] struct {
	Current  *T
	Previous *T
	Metric   metrics.MetricDef
}

type Number added in v0.4.0

type Number interface {
	~int64 | ~float64
}

Jump to

Keyboard shortcuts

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