db

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ColumnInfo

type ColumnInfo struct {
	Name      string
	DataType  string
	Nullable  bool
	Default   string
	IsPrimary bool
}

ColumnInfo describes a single column in a table.

type ConnectionGroup

type ConnectionGroup struct {
	User  string
	App   string
	State string
	Count int
}

ConnectionGroup is an aggregated view of connections sharing the same user, application, and state.

type DB

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

DB wraps a pgxpool.Pool and provides query helpers for Tusk.

func New

func New(connString string) (*DB, error)

New creates a new connection pool to the PostgreSQL instance identified by connString. The pool is limited to 3 connections and each connection sets a 2-second statement_timeout on creation.

func (*DB) CancelQuery

func (d *DB) CancelQuery(ctx context.Context, pid int) error

CancelQuery sends pg_cancel_backend for the given PID.

func (*DB) Close

func (d *DB) Close()

Close releases all connections in the pool.

func (*DB) GetActiveQueries

func (d *DB) GetActiveQueries(ctx context.Context) ([]Query, error)

GetActiveQueries returns all active backends from pg_stat_activity, excluding the caller's own connection.

func (*DB) GetConnections

func (d *DB) GetConnections(ctx context.Context) ([]ConnectionGroup, error)

GetConnections returns connections grouped by user, application, and state.

func (*DB) GetDatabaseStats

func (d *DB) GetDatabaseStats(ctx context.Context) (*DatabaseStats, error)

GetDatabaseStats returns activity counters for the current database.

func (*DB) GetDatabases

func (d *DB) GetDatabases(ctx context.Context) ([]DatabaseInfo, error)

GetDatabases returns all non-template databases with their sizes.

func (*DB) GetIndexes

func (d *DB) GetIndexes(ctx context.Context) ([]IndexInfo, error)

GetIndexes returns per-index statistics from pg_stat_user_indexes.

func (*DB) GetLocks

func (d *DB) GetLocks(ctx context.Context) ([]Lock, error)

GetLocks returns information about blocked locks and their blockers.

func (*DB) GetRoles

func (d *DB) GetRoles(ctx context.Context) ([]RoleInfo, error)

GetRoles returns all roles and their key privileges.

func (*DB) GetServerInfo

func (d *DB) GetServerInfo(ctx context.Context) (*ServerInfo, error)

GetServerInfo returns the server version, uptime, and max_connections.

func (*DB) GetSlowQueries

func (d *DB) GetSlowQueries(ctx context.Context) ([]SlowQuery, error)

GetSlowQueries returns the top 50 queries by total execution time from pg_stat_statements. Returns an empty slice if the extension is not installed.

func (*DB) GetTableDetail

func (d *DB) GetTableDetail(ctx context.Context, schema, name string) (*TableDetail, error)

GetTableDetail returns detailed information about a single table including columns, indexes, and statistics.

func (*DB) GetTables

func (d *DB) GetTables(ctx context.Context) ([]TableInfo, error)

GetTables returns per-table statistics from pg_stat_user_tables.

func (*DB) GetTransactions

func (d *DB) GetTransactions(ctx context.Context) ([]Transaction, error)

GetTransactions returns all active transactions from pg_stat_activity.

func (*DB) Pool

func (d *DB) Pool() *pgxpool.Pool

Pool returns the underlying pgxpool.Pool.

func (*DB) TerminateBackend

func (d *DB) TerminateBackend(ctx context.Context, pid int) error

TerminateBackend sends pg_terminate_backend for the given PID.

type DatabaseInfo

type DatabaseInfo struct {
	Name  string
	Size  int64
	Owner string
}

DatabaseInfo describes a single non-template database.

type DatabaseStats

type DatabaseStats struct {
	XactCommit    int64
	XactRollback  int64
	BlksHit       int64
	BlksRead      int64
	CacheHitRatio float64
}

DatabaseStats holds activity counters for a single database.

type IndexInfo

type IndexInfo struct {
	Schema    string
	Table     string
	IndexName string
	Scans     int64
	TupRead   int64
	TupFetch  int64
	Size      int64
}

IndexInfo holds per-index statistics from pg_stat_user_indexes.

type Lock

type Lock struct {
	BlockedPID    int
	BlockingPID   int
	BlockedUser   string
	BlockingUser  string
	BlockedApp    string
	BlockingApp   string
	LockType      string
	Mode          string
	WaitDuration  time.Duration
	BlockedQuery  string
	BlockingQuery string
}

Lock describes a blocked lock and the backend blocking it.

type Query

type Query struct {
	ResourceBase
	Duration      time.Duration
	QueryStart    time.Time // when this query started executing
	WaitEventType string
	WaitEvent     string
	QueryText     string
	Comment       SQLComment
	BlockedBy     int
	QueryID       int64
}

Query represents a single in-flight backend from pg_stat_activity.

type QueryHistory

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

QueryHistory tracks the sequence of queries observed per backend session. Each session keeps a ring buffer of the last N distinct queries.

func NewQueryHistory

func NewQueryHistory(maxPerSession int) *QueryHistory

NewQueryHistory creates a new query history tracker.

func (*QueryHistory) Cleanup

func (h *QueryHistory) Cleanup(activeKeys map[sessionKey]bool)

Cleanup removes entries for sessions that are no longer active.

func (*QueryHistory) Get

func (h *QueryHistory) Get(pid int, backendStart time.Time) []QueryHistoryEntry

Get returns the query history for a backend session (oldest first).

func (*QueryHistory) Record

func (h *QueryHistory) Record(pid int, backendStart time.Time, query, state string)

Record adds a query observation for a backend session. Only records if the query text differs from the last recorded entry.

func (*QueryHistory) RecordAll

func (h *QueryHistory) RecordAll(queries []Query)

RecordAll records observations from a slice of active queries.

func (*QueryHistory) RecordTransactions

func (h *QueryHistory) RecordTransactions(txns []Transaction)

RecordTransactions records observations from a slice of transactions. Uses XactStart as the session key so each transaction gets its own history.

type QueryHistoryEntry

type QueryHistoryEntry struct {
	Query     string
	State     string
	Timestamp time.Time
}

QueryHistoryEntry records a query observed for a backend at a point in time.

type ResourceBase

type ResourceBase struct {
	PID          int
	User         string
	App          string
	Database     string
	ClientAddr   string
	State        string
	BackendStart time.Time // when this backend process started — unique with PID
}

ResourceBase contains fields shared across all pg_stat_activity-derived resources.

type RoleInfo

type RoleInfo struct {
	Name          string
	IsSuperuser   bool
	CanCreateRole bool
	CanCreateDB   bool
	CanLogin      bool
	ConnLimit     int
}

RoleInfo describes a PostgreSQL role and its key privileges.

type SQLComment

type SQLComment struct {
	App        string
	Route      string
	Controller string
	Action     string
	Framework  string
}

SQLComment holds metadata extracted from a SQLcommentor-style comment appended to a query string.

func ParseSQLComment

func ParseSQLComment(query string) SQLComment

ParseSQLComment extracts SQLcommentor key-value pairs from the trailing block comment of a SQL query. Returns an empty SQLComment if no comment is found.

type ServerInfo

type ServerInfo struct {
	Version        string
	Uptime         time.Duration
	MaxConnections int
}

ServerInfo holds high-level PostgreSQL server metadata.

type SlowQuery

type SlowQuery struct {
	QueryID   int64
	Query     string
	Calls     int64
	TotalTime float64
	MeanTime  float64
	Rows      int64
	HitRatio  float64
}

SlowQuery holds a row from pg_stat_statements ordered by total execution time.

type TableDetail

type TableDetail struct {
	Schema         string
	Name           string
	TotalSize      int64
	LiveTuples     int64
	DeadTuples     int64
	SeqScan        int64
	IdxScan        int64
	LastVacuum     *time.Time
	LastAutoVacuum *time.Time
	LastAnalyze    *time.Time
	Columns        []ColumnInfo
	Indexes        []IndexInfo
}

TableDetail holds detailed information about a single table.

type TableInfo

type TableInfo struct {
	Schema         string
	Name           string
	TotalSize      int64
	LiveTuples     int64
	DeadTuples     int64
	SeqScan        int64
	IdxScan        int64
	LastVacuum     *time.Time
	LastAutoVacuum *time.Time
}

TableInfo holds per-table statistics from pg_stat_user_tables.

type Transaction

type Transaction struct {
	ResourceBase
	XactStart     time.Time // when this transaction began — unique with PID
	XactDuration  time.Duration
	QueryDuration time.Duration
	QueryText     string
	LockCount     int
}

Transaction represents an active transaction from pg_stat_activity.

Jump to

Keyboard shortcuts

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