Documentation
¶
Overview ¶
Package db manages pgx connection pools per database and exposes the administration queries used by the TUI.
Index ¶
- Constants
- Variables
- func ApplyHBAContent(ctx context.Context, mgr *Manager, dsn, newContent string) error
- func BuildAlterRoleAttrs(name string, from, to RoleAttrs) string
- func BuildAlterRolePassword(name, secret string) string
- func BuildAlterSystemReset(name string) string
- func BuildAlterSystemSet(name, value string) string
- func BuildCreateDatabase(name, owner string) string
- func BuildCreateRole(name, password string, login, createdb, createrole bool) string
- func BuildDatabaseConnLimit(dbname string, limit int) string
- func BuildDropDatabase(name string) string
- func BuildDropRole(name string) string
- func BuildGrant(scope GrantScope, database, role string) (targetDB string, stmts []string)
- func BuildHBALine(r HBARuleInput) string
- func BuildRevoke(scope GrantScope, database, role string) (targetDB string, stmts []string)
- func BuildRoleConnLimit(role string, limit int) string
- func CancelBackend(ctx context.Context, p Pinger, pid int32) (bool, error)
- func ClampSCRAMIterations(n int) int
- func ConnectableDatabases(ctx context.Context, p Pinger) ([]string, error)
- func DatabasesOwnedBy(ctx context.Context, p Pinger, role string) ([]string, error)
- func ExecAdmin(ctx context.Context, p Pinger, sql string) (string, error)
- func ForceDropRole(ctx context.Context, mgr *Manager, doomed, successor string) ([]string, error)
- func GeneratePassword(n int) (string, error)
- func HBAAppendLine(content, line string) string
- func HBADeleteLine(content string, lineNum int) (string, error)
- func HBAFileContent(ctx context.Context, p Pinger) (string, error)
- func HBAFilePath(ctx context.Context, p Pinger) (string, error)
- func HBAReplaceLine(content string, lineNum int, newLine string) (string, error)
- func HBAWritable(ctx context.Context, p Pinger) bool
- func PasswordSecret(plaintext string, iterations int) (secret string, hashed bool, err error)
- func QuoteIdent(s string) string
- func QuoteLiteral(s string) string
- func QuoteQualified(schema, name string) string
- func ReadSettings(ctx context.Context, p Pinger, names []string) (map[string]RawSetting, error)
- func ReadTuningSettings(ctx context.Context, p Pinger) (map[string]RawSetting, error)
- func ReloadConf(ctx context.Context, p Pinger) error
- func SCRAMSHA256Secret(password string, iterations int) (secret string, rounds int, err error)
- func TerminateBackend(ctx context.Context, p Pinger, pid int32) (bool, error)
- func ValidateSettingValue(s Setting, value string) error
- type BlockPair
- type ColumnDef
- type ConnClientGroup
- type ConnError
- type ConnErrorKind
- type ConnFinding
- type ConnHeadroom
- type ConnStateCount
- type ConstraintDef
- type DBAccess
- type Danger
- type DashboardData
- type Database
- type GrantScope
- type HBARule
- type HBARuleInput
- type IndexDef
- type LocalSocket
- type Manager
- type Pinger
- type ProbeResult
- type QueryResult
- type RawSetting
- type Replica
- type Role
- type RoleAttrs
- type Session
- type Setting
- type Table
- type TableDescription
- type TablePriv
- type TuningInput
- type TuningRec
- type Verdict
Constants ¶
const ( // SCRAMDefaultIterations is the PBKDF2 iteration count ("rounds") used when // none is configured. It sits above PostgreSQL's own default of 4096 (and // above NIST SP 800-63B's 10000 minimum) to make the stored verifier // costlier to brute-force, while staying cheap enough that the server's // per-login verification stays in the low-millisecond range. Override with // the PGTOWER_SCRAM_ITERATIONS environment variable. SCRAMDefaultIterations = 15000 )
Variables ¶
var SocketDirs = []string{"/var/run/postgresql", "/run/postgresql", "/tmp", "/private/tmp"}
SocketDirs are where PostgreSQL puts its unix socket by default: the Debian/Ubuntu and RHEL packages use /var/run/postgresql (/run/postgresql); source builds, Homebrew and Postgres.app use /tmp.
Functions ¶
func ApplyHBAContent ¶
ApplyHBAContent rewrites pg_hba.conf with newContent, guarded by a safety net: it backs up the file, writes the new content, checks pg_hba_file_rules for parse errors, reloads, and opens a FRESH admin connection to confirm login still works. Any failure restores the backup and reloads, so a bad edit can't lock you out. Returns a descriptive error on rollback.
func BuildAlterRoleAttrs ¶
BuildAlterRoleAttrs builds an ALTER ROLE that flips only the attributes that differ between `from` and `to`. It returns "" when nothing changed.
Emitting only the differences is deliberate. Restating every attribute would need privileges the caller may not have (NOSUPERUSER requires superuser even when it is already off) and would hide, in the audit trail, which attribute the operator actually meant to change.
func BuildAlterRolePassword ¶
BuildAlterRolePassword builds an ALTER ROLE ... PASSWORD statement to reset a role's password. The secret is quoted as a SQL string literal. It may be a plaintext password or a pre-computed verifier (e.g. from SCRAMSHA256Secret): when it is a valid "SCRAM-SHA-256$..." string PostgreSQL stores it verbatim, so the plaintext never reaches the server.
func BuildAlterSystemReset ¶
BuildAlterSystemReset builds ALTER SYSTEM RESET name (reverts to the default).
func BuildAlterSystemSet ¶
BuildAlterSystemSet builds ALTER SYSTEM SET name = 'value'. The value is quoted as a literal, which Postgres coerces for any GUC type.
func BuildCreateDatabase ¶
BuildCreateDatabase builds a CREATE DATABASE (optional owner).
func BuildCreateRole ¶
BuildCreateRole builds a CREATE ROLE. login controls LOGIN/NOLOGIN; an empty password omits PASSWORD. createdb/createrole add the attributes.
func BuildDatabaseConnLimit ¶
BuildDatabaseConnLimit builds ALTER DATABASE ... CONNECTION LIMIT. -1 = unlimited.
func BuildDropDatabase ¶
BuildDropDatabase builds a DROP DATABASE.
func BuildGrant ¶
func BuildGrant(scope GrantScope, database, role string) (targetDB string, stmts []string)
BuildGrant returns the database the statements should run on ("" = can run on admin) and the list of statements for the chosen preset.
func BuildHBALine ¶
func BuildHBALine(r HBARuleInput) string
BuildHBALine renders an HBARuleInput as a single pg_hba.conf line. local rules omit the address field.
func BuildRevoke ¶
func BuildRevoke(scope GrantScope, database, role string) (targetDB string, stmts []string)
BuildRevoke mirrors BuildGrant. It returns no statements for GrantOwner, which is a transfer rather than a privilege.
Each preset also undoes the matching ALTER DEFAULT PRIVILEGES. Without that, revoking looks like it worked and the role silently keeps access to every table created afterwards — the failure mode that makes "granted once, stuck forever" so hard to see.
func BuildRoleConnLimit ¶
BuildRoleConnLimit builds ALTER ROLE ... CONNECTION LIMIT. -1 means unlimited.
func CancelBackend ¶
CancelBackend sends SIGINT (pg_cancel_backend) — cancels the session's current query without dropping it. Requires being the session owner, a member of the owning role, or pg_signal_backend/superuser.
func ClampSCRAMIterations ¶
ClampSCRAMIterations maps a requested iteration count to the effective one: 0 (unset) -> SCRAMDefaultIterations, below the floor -> scramMinIterations, above the ceiling -> scramMaxIterations.
func ConnectableDatabases ¶
ConnectableDatabases returns the non-template databases that accept connections.
func DatabasesOwnedBy ¶
DatabasesOwnedBy returns the (non-template) databases owned by the role.
func ExecAdmin ¶
ExecAdmin runs an administrative statement (CREATE/DROP/GRANT/ALTER) in the simple protocol. Required because CREATE/DROP DATABASE do not run in pgx's extended protocol (prepared statement). It only receives SQL built internally (quoted identifiers), never raw user input.
func ForceDropRole ¶
ForceDropRole removes a role even with dependencies, WITHOUT dropping data: it reassigns ownership of the databases and objects to the successor, revokes the role's privileges in each database, and finally runs DROP ROLE. It returns non-fatal warnings per database and the final DROP ROLE error (if any).
func GeneratePassword ¶
GeneratePassword returns a cryptographically-random password of length n built only from terminal-safe characters (see passwordAlphabet). n <= 0 defaults to 32. It returns an error only if the system CSPRNG fails.
func HBAAppendLine ¶
HBAAppendLine appends a rule line to the file content (ensuring a trailing newline).
func HBADeleteLine ¶
HBADeleteLine removes the 1-based physical line lineNum.
func HBAFileContent ¶
HBAFileContent returns the raw text of pg_hba.conf (superuser / pg_read_server_files).
func HBAFilePath ¶
HBAFilePath returns the path of the active pg_hba.conf.
func HBAReplaceLine ¶
HBAReplaceLine replaces the 1-based physical line lineNum with newLine.
func HBAWritable ¶
HBAWritable reports whether this connection can rewrite server files. Editing uses COPY ... TO PROGRAM, which requires a superuser (or pg_execute_server_program).
func PasswordSecret ¶
PasswordSecret encodes a plaintext for a PASSWORD clause (CREATE/ALTER ROLE). When the plaintext is printable ASCII — the range for which SASLprep (RFC 4013) is the identity, so a client-computed verifier matches what the server expects at login — it returns the SCRAM-SHA-256 verifier and hashed=true, keeping the plaintext off the wire and out of the server log. Otherwise (non-ASCII, or empty) it returns the plaintext unchanged with hashed=false, letting the server SASLprep and hash it correctly. Callers pass the result straight to BuildCreateRole/BuildAlterRolePassword; an empty plaintext yields "" so the PASSWORD clause is omitted.
func QuoteIdent ¶
QuoteIdent quotes a SQL identifier (table, column, role, db name).
func QuoteLiteral ¶
QuoteLiteral quotes a SQL string literal (doubles single quotes).
func QuoteQualified ¶
QuoteQualified quotes schema.table.
func ReadSettings ¶
ReadSettings returns the named GUCs from pg_settings as name -> value/unit.
func ReadTuningSettings ¶
ReadTuningSettings reads the curated set of GUCs the advisor needs.
func ReloadConf ¶
ReloadConf asks the server to reload configuration (pg_reload_conf), applying sighup-context changes without a restart.
func SCRAMSHA256Secret ¶
SCRAMSHA256Secret computes the SCRAM-SHA-256 verifier for a password in the exact textual form PostgreSQL stores in pg_authid.rolpassword:
SCRAM-SHA-256$<iterations>:<base64 salt>$<base64 StoredKey>:<base64 ServerKey>
Passing this string to `ALTER ROLE ... PASSWORD` makes the server store it verbatim (it recognises the format) instead of hashing a plaintext. The usable password therefore never travels to — nor can be logged by — the server; only the irreversible verifier does.
iterations is clamped to a safe range by ClampSCRAMIterations (pass 0 to use SCRAMDefaultIterations). It returns the verifier and the effective iteration count actually used, so callers can surface it.
The password is assumed to be ASCII, for which SASLprep (RFC 4013) is the identity function. Generated passwords are letters and digits only, so this always holds here.
func TerminateBackend ¶
TerminateBackend sends SIGTERM (pg_terminate_backend) — drops the connection.
func ValidateSettingValue ¶
ValidateSettingValue checks a proposed value against a Setting's type and bounds. It is pure/auditable. Values carrying a unit suffix (e.g. "8MB") for numeric GUCs are left for the server to validate.
Types ¶
type BlockPair ¶
type BlockPair struct {
BlockedPID int32
BlockedUser string
BlockedDB string
BlockedFor string
BlockedQuery string
BlockingPID int32
BlockingUser string
BlockingSt string
BlockingQ string
}
BlockPair describes a blocked session and the session blocking it.
type ConnClientGroup ¶
ConnClientGroup groups client backends by who/what opened them.
func ConnByClient ¶
func ConnByClient(ctx context.Context, p Pinger) ([]ConnClientGroup, error)
ConnByClient groups client backends by user, database, application and state, most connections first — the breakdown that reveals which app is hogging slots.
type ConnError ¶
type ConnError struct {
Kind ConnErrorKind
Title string
Detail string
Hint string
Err error
}
ConnError is a connection failure explained for a human: what happened, the likely cause, and what to check next. The raw driver error stays available via Unwrap (and Cause) for the details view.
func ExplainConnect ¶
ExplainConnect turns a raw connect/ping error into a ConnError. host and port are what the user configured (a unix-socket directory is a valid host).
type ConnErrorKind ¶
type ConnErrorKind string
ConnErrorKind classifies why a connection could not be established.
const ( ConnTimeout ConnErrorKind = "timeout" ConnRefused ConnErrorKind = "refused" ConnUnreachable ConnErrorKind = "unreachable" ConnUnknownHost ConnErrorKind = "unknown-host" ConnNoSocket ConnErrorKind = "no-socket" ConnAuth ConnErrorKind = "auth" ConnRejected ConnErrorKind = "rejected" ConnNoDatabase ConnErrorKind = "no-database" ConnTooMany ConnErrorKind = "too-many" ConnStarting ConnErrorKind = "starting" ConnTLS ConnErrorKind = "tls" ConnOther ConnErrorKind = "other" )
type ConnFinding ¶
ConnFinding is one diagnostic about connection usage. Level is "info" | "warn" | "crit".
func AnalyzeConnections ¶
func AnalyzeConnections(h ConnHeadroom) []ConnFinding
AnalyzeConnections turns a headroom snapshot into actionable findings. It is pure (no I/O) so its advice is unit-testable and auditable.
type ConnHeadroom ¶
type ConnHeadroom struct {
MaxConnections int
Reserved int // superuser_reserved_connections (+ reserved_connections, PG16)
Used int
Active int
Idle int
IdleInTx int
}
ConnHeadroom summarizes connection capacity versus current usage. Used counts client backends only (excludes autovacuum/background workers).
func GetConnHeadroom ¶
func GetConnHeadroom(ctx context.Context, p Pinger) (ConnHeadroom, error)
GetConnHeadroom reads the connection limits and the current client-backend usage in a single round-trip. reserved_connections exists only on PG16+; it reads as 0 elsewhere.
type ConnStateCount ¶
ConnStateCount is the number of client backends in a given state, plus the age (seconds) of the oldest one in that bucket.
func ConnStateSummary ¶
func ConnStateSummary(ctx context.Context, p Pinger) ([]ConnStateCount, error)
ConnStateSummary returns the client-backend count per state, busiest first.
type ConstraintDef ¶
ConstraintDef describes a constraint (PK/FK/UNIQUE/CHECK).
type DBAccess ¶
type DBAccess struct {
Database string
IsOwner bool
DBPrivs []string // explicit database grants (CONNECT / CREATE / TEMPORARY)
Schema []string // explicit privileges on schema public (USAGE / CREATE)
Tables []TablePriv // per-privilege table counts in schema public
Err string // set when the per-database probe failed
}
DBAccess summarizes what access a role has to one database: ownership, explicit database-level grants, and the explicit schema/table privileges found inside that database.
func RoleAccess ¶
RoleAccess reports, per database, where a role has been granted access: ownership and explicit database-level grants (read once from the admin connection), plus the explicit schema/table privileges probed inside each connectable database. Databases where the role has nothing explicit are omitted. PUBLIC usually holds CONNECT, so a role may still connect to a database that does not appear here — the caller should say so.
type Danger ¶
type Danger int
Danger classifies the risk of a SQL statement for the query runner.
const ( // Safe: read-only (SELECT/WITH...SELECT/EXPLAIN/SHOW/TABLE/VALUES). Safe Danger = iota // Write: modifies data or schema (INSERT/UPDATE/DELETE/DDL). Confirmation. Write // Critical: potential mass data loss (DROP DATABASE/TABLE, // TRUNCATE, DELETE/UPDATE without WHERE). Emphatic confirmation. Critical )
type DashboardData ¶
type DashboardData struct {
Version string
StartedAt time.Time
Uptime time.Duration
MaxConns int
Reserved int // superuser_reserved_connections (+ reserved_connections, PG16)
TotalConns int
OwnConns int // backends opened by pgtower itself (application_name = 'pgtower')
Active int
Idle int
IdleInTx int
CacheHitRatio float64 // percentage
Commits int64
Rollbacks int64
DBCount int
TotalSize string
LongestQuery time.Duration
Replicas []Replica
}
DashboardData aggregates cluster health metrics.
func LoadDashboard ¶
func LoadDashboard(ctx context.Context, p Pinger) (DashboardData, error)
LoadDashboard collects the cluster metrics from the admin database.
type GrantScope ¶
type GrantScope int
GrantScope defines the GRANT presets between role and database.
const ( GrantConnect GrantScope = iota // GRANT CONNECT ON DATABASE GrantAllDatabase // GRANT ALL PRIVILEGES ON DATABASE GrantOwner // ALTER DATABASE ... OWNER TO GrantSchemaAll // full access to the public schema (runs on the target db) GrantSchemaReadWrite // read/write rows, no DDL (runs on the target db) GrantSchemaReadOnly // read-only (SELECT), no writes (runs on the target db) )
func (GrantScope) Label ¶
func (g GrantScope) Label() string
func (GrantScope) Revocable ¶
func (g GrantScope) Revocable() bool
Revocable reports whether the scope has a REVOKE counterpart. Ownership is a transfer, not a privilege: it is undone by handing the database to someone else, never by revoking it.
type HBARule ¶
type HBARule struct {
LineNumber int
Type string
Database string
UserName string
Address string
Netmask string
AuthMethod string
Options string
Error string
}
HBARule is a parsed pg_hba.conf line as reported by pg_hba_file_rules. Error is non-empty when Postgres failed to parse that line.
type HBARuleInput ¶
type HBARuleInput struct {
Type string // local | host | hostssl | hostnossl | ...
Database string
User string
Address string // empty for local
Method string // trust | scram-sha-256 | md5 | peer | reject | ...
}
HBARuleInput describes a rule to build a pg_hba.conf line from.
type LocalSocket ¶ added in v0.11.0
type LocalSocket struct {
Dir string // the directory, which is what goes in a connection's host
Port int
}
LocalSocket is a PostgreSQL unix socket found on this machine.
func LocalSockets ¶ added in v0.11.0
func LocalSockets() []LocalSocket
LocalSockets lists the PostgreSQL sockets in SocketDirs, in that order and lowest port first within a directory. A directory reached twice through a symlink (/var/run → /run) is listed once, under its first name.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager keeps one pool per database. The first pool (AdminDB) is used for cluster queries; additional pools are created on demand when navigating to another database's tables or running queries against it.
func NewManager ¶
NewManager parses the base DSN and opens the administrative database's pool, validating connectivity with a ping.
type Pinger ¶
type Pinger interface {
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
}
Pinger abstracts *pgxpool.Pool to ease testing and reuse.
type ProbeResult ¶
ProbeResult is what "test connection" reports.
type QueryResult ¶
type QueryResult struct {
Columns []string
Rows [][]string // display text: one line per cell, NULL as ∅, bytea abbreviated
Raw [][]string // full text of each cell, for copying: "" for NULL (see maxCopyCell)
Command string // command tag (e.g. "UPDATE 3") for statements without a result
RowCount int // rows returned (SELECT) or affected
Elapsed time.Duration
Truncated bool
}
QueryResult carries the result of an ad-hoc query.
type RawSetting ¶
RawSetting is a GUC's current value and unit as reported by pg_settings.
type Role ¶
type Role struct {
Name string
CanLogin bool
Super bool
CreateDB bool
CreateRole bool
Replication bool
// BypassRLS means the role ignores row-level security. Listing it matters as
// much as SUPERUSER: on a database whose tenant isolation rests on RLS, one
// role with this attribute reads every tenant's rows and nothing errors.
BypassRLS bool
ConnLimit int
ValidUntil string
MemberOf string
}
Role is a row from pg_roles.
type RoleAttrs ¶
type RoleAttrs struct {
Login bool
CreateDB bool
CreateRole bool
Superuser bool
Replication bool
BypassRLS bool
}
RoleAttrs are the boolean attributes of a role that ALTER ROLE can flip.
type Session ¶
type Session struct {
PID int32
User string
DB string
AppName string
ClientAddr string
State string
Wait string
Duration string // now - query_start
Query string
}
Session is a row from pg_stat_activity (client connection).
type Setting ¶
type Setting struct {
Name string
Setting string
Unit string
Context string // internal|postmaster|sighup|superuser|backend|user|...
VarType string // bool|integer|real|enum|string
Category string
ShortDesc string
MinVal string
MaxVal string
EnumVals []string
BootVal string
ResetVal string
PendingRestart bool
}
Setting is a full pg_settings row for the ALTER SYSTEM editor.
func ListAllSettings ¶
ListAllSettings returns every GUC from pg_settings, ordered by name.
func (Setting) Changeable ¶
Changeable reports whether the GUC can be changed at all (internal settings are compile-time and cannot).
func (Setting) NeedsRestart ¶
NeedsRestart reports whether changing the GUC only takes effect after a full server restart (context = postmaster).
type Table ¶
type Table struct {
Schema string
Name string
TotalBytes int64
TotalSize string
TableSize string
IndexSize string
EstRows int64
}
Table is a row in a database's table list.
type TableDescription ¶
type TableDescription struct {
Schema string
Table string
Columns []ColumnDef
Indexes []IndexDef
Constraints []ConstraintDef
}
TableDescription is the "\d" of a table.
func DescribeTable ¶
DescribeTable returns the columns, indexes and constraints of a table.
type TuningInput ¶
type TuningInput struct {
RAMBytes int64
CPUs int
MaxConnections int
EffectiveCache int64
WorkMem int64
MaintWorkMem int64
}
TuningInput is what the recommender needs. RAMBytes/CPUs == 0 means unknown (Postgres can't report the host's RAM/cores, so they come from config/env).
func BuildTuningInput ¶
func BuildTuningInput(m map[string]RawSetting, ramBytes int64, cpus int) TuningInput
BuildTuningInput assembles a TuningInput from raw pg_settings values plus the host RAM/cores. It is pure so it can be unit-tested.
type TuningRec ¶
TuningRec is one advisor row: what it is now, what's recommended, a verdict and a short explanation.
func Recommend ¶
func Recommend(in TuningInput) []TuningRec
Recommend produces the advisor rows. It is pure (no I/O) so the advice is fully unit-testable. When RAM/CPUs are unknown it still does the checks that don't need them and marks the rest as info with a hint.