db

package
v0.13.1 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 25 Imported by: 0 modules, 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 manages pgx connection pools per database and exposes the administration queries used by the TUI.

Index

Constants

View Source
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

View Source
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

func ApplyHBAContent(ctx context.Context, mgr *Manager, dsn, newContent string) error

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

func BuildAlterRoleAttrs(name string, from, to RoleAttrs) string

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

func BuildAlterRolePassword(name, secret string) string

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

func BuildAlterSystemReset(name string) string

BuildAlterSystemReset builds ALTER SYSTEM RESET name (reverts to the default).

func BuildAlterSystemSet

func BuildAlterSystemSet(name, value string) string

BuildAlterSystemSet builds ALTER SYSTEM SET name = 'value'. The value is quoted as a literal, which Postgres coerces for any GUC type.

func BuildCreateDatabase

func BuildCreateDatabase(name, owner string) string

BuildCreateDatabase builds a CREATE DATABASE (optional owner).

func BuildCreateRole

func BuildCreateRole(name, password string, login, createdb, createrole bool) string

BuildCreateRole builds a CREATE ROLE. login controls LOGIN/NOLOGIN; an empty password omits PASSWORD. createdb/createrole add the attributes.

func BuildDatabaseConnLimit

func BuildDatabaseConnLimit(dbname string, limit int) string

BuildDatabaseConnLimit builds ALTER DATABASE ... CONNECTION LIMIT. -1 = unlimited.

func BuildDropDatabase

func BuildDropDatabase(name string) string

BuildDropDatabase builds a DROP DATABASE.

func BuildDropRole

func BuildDropRole(name string) string

BuildDropRole builds a DROP ROLE.

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

func BuildRoleConnLimit(role string, limit int) string

BuildRoleConnLimit builds ALTER ROLE ... CONNECTION LIMIT. -1 means unlimited.

func CancelBackend

func CancelBackend(ctx context.Context, p Pinger, pid int32) (bool, error)

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

func ClampSCRAMIterations(n int) int

ClampSCRAMIterations maps a requested iteration count to the effective one: 0 (unset) -> SCRAMDefaultIterations, below the floor -> scramMinIterations, above the ceiling -> scramMaxIterations.

func ConnectableDatabases

func ConnectableDatabases(ctx context.Context, p Pinger) ([]string, error)

ConnectableDatabases returns the non-template databases that accept connections.

func DatabasesOwnedBy

func DatabasesOwnedBy(ctx context.Context, p Pinger, role string) ([]string, error)

DatabasesOwnedBy returns the (non-template) databases owned by the role.

func ExecAdmin

func ExecAdmin(ctx context.Context, p Pinger, sql string) (string, error)

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

func ForceDropRole(ctx context.Context, mgr *Manager, doomed, successor string) ([]string, error)

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

func GeneratePassword(n int) (string, error)

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

func HBAAppendLine(content, line string) string

HBAAppendLine appends a rule line to the file content (ensuring a trailing newline).

func HBADeleteLine

func HBADeleteLine(content string, lineNum int) (string, error)

HBADeleteLine removes the 1-based physical line lineNum.

func HBAFileContent

func HBAFileContent(ctx context.Context, p Pinger) (string, error)

HBAFileContent returns the raw text of pg_hba.conf (superuser / pg_read_server_files).

func HBAFilePath

func HBAFilePath(ctx context.Context, p Pinger) (string, error)

HBAFilePath returns the path of the active pg_hba.conf.

func HBAReplaceLine

func HBAReplaceLine(content string, lineNum int, newLine string) (string, error)

HBAReplaceLine replaces the 1-based physical line lineNum with newLine.

func HBAWritable

func HBAWritable(ctx context.Context, p Pinger) bool

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

func PasswordSecret(plaintext string, iterations int) (secret string, hashed bool, err error)

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

func QuoteIdent(s string) string

QuoteIdent quotes a SQL identifier (table, column, role, db name).

func QuoteLiteral

func QuoteLiteral(s string) string

QuoteLiteral quotes a SQL string literal (doubles single quotes).

func QuoteQualified

func QuoteQualified(schema, name string) string

QuoteQualified quotes schema.table.

func ReadSettings

func ReadSettings(ctx context.Context, p Pinger, names []string) (map[string]RawSetting, error)

ReadSettings returns the named GUCs from pg_settings as name -> value/unit.

func ReadTuningSettings

func ReadTuningSettings(ctx context.Context, p Pinger) (map[string]RawSetting, error)

ReadTuningSettings reads the curated set of GUCs the advisor needs.

func ReloadConf

func ReloadConf(ctx context.Context, p Pinger) error

ReloadConf asks the server to reload configuration (pg_reload_conf), applying sighup-context changes without a restart.

func SCRAMSHA256Secret

func SCRAMSHA256Secret(password string, iterations int) (secret string, rounds int, err error)

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

func TerminateBackend(ctx context.Context, p Pinger, pid int32) (bool, error)

TerminateBackend sends SIGTERM (pg_terminate_backend) — drops the connection.

func ValidateSettingValue

func ValidateSettingValue(s Setting, value string) error

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.

func ListBlocks

func ListBlocks(ctx context.Context, p Pinger) ([]BlockPair, error)

ListBlocks returns the current blocking tree (who waits on whom).

type ColumnDef

type ColumnDef struct {
	Name     string
	Type     string
	Nullable bool
	Default  string
}

ColumnDef describes a table column.

type ConnClientGroup

type ConnClientGroup struct {
	User  string
	DB    string
	App   string
	State string
	Count int
}

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

func ExplainConnect(err error, host, port string) *ConnError

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).

func (*ConnError) Cause

func (e *ConnError) Cause() string

Cause is the underlying driver error text, for "technical details".

func (*ConnError) Error

func (e *ConnError) Error() string

func (*ConnError) Unwrap

func (e *ConnError) Unwrap() error

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

type ConnFinding struct {
	Level string
	Msg   string
}

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

type ConnStateCount struct {
	State     string
	Count     int
	OldestSec float64
}

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

type ConstraintDef struct {
	Name string
	Type string // p, f, u, c, ...
	Def  string
}

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

func RoleAccess(ctx context.Context, mgr *Manager, role string) ([]DBAccess, error)

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
)

func Classify

func Classify(sql string) Danger

Classify determines the risk level of a statement. It does a simple lexical analysis (not a SQL parser) — when in doubt, it escalates the risk.

func (Danger) String

func (d Danger) String() string

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 Database

type Database struct {
	Name        string
	Owner       string
	SizeBytes   int64
	SizePretty  string
	Connections int
}

Database is a row in the database list.

func ListDatabases

func ListDatabases(ctx context.Context, p Pinger) ([]Database, error)

ListDatabases returns all non-template databases ordered by size.

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.

func ListHBARules

func ListHBARules(ctx context.Context, p Pinger) ([]HBARule, error)

ListHBARules returns the parsed authentication rules (pg_hba_file_rules, PG10+). Requires superuser. array columns are flattened to comma lists.

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 IndexDef

type IndexDef struct {
	Name string
	Def  string
}

IndexDef describes an index.

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

func NewManager(ctx context.Context, dsn, adminDB string) (*Manager, error)

NewManager parses the base DSN and opens the administrative database's pool, validating connectivity with a ping.

func (*Manager) AdminDB

func (m *Manager) AdminDB() string

AdminDB returns the name of the administrative database.

func (*Manager) Close

func (m *Manager) Close()

Close closes all open pools.

func (*Manager) Pool

func (m *Manager) Pool(ctx context.Context, dbname string) (*pgxpool.Pool, error)

Pool returns (creating it if necessary) the pool for the given database.

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

type ProbeResult struct {
	Latency time.Duration
	Version string
}

ProbeResult is what "test connection" reports.

func Probe

func Probe(ctx context.Context, dsn, host, port string) (ProbeResult, error)

Probe opens one short-lived connection, reads the server version and closes it. Errors come back already explained.

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.

func RunQuery

func RunQuery(ctx context.Context, p Pinger, sql string) (QueryResult, error)

RunQuery runs arbitrary SQL on the given pool and returns the (limited) rows or the command tag. It uses a statement timeout to avoid hanging.

type RawSetting

type RawSetting struct {
	Setting string
	Unit    string
}

RawSetting is a GUC's current value and unit as reported by pg_settings.

type Replica

type Replica struct {
	ClientAddr string
	State      string
	SyncState  string
	Lag        string
}

Replica describes a standby connected via streaming replication.

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.

func ListRoles

func ListRoles(ctx context.Context, p Pinger) ([]Role, error)

ListRoles lists the cluster roles.

func (Role) Attrs

func (r Role) Attrs() RoleAttrs

Attrs returns the role's current attributes.

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.

func (RoleAttrs) Escalates

func (a RoleAttrs) Escalates(from RoleAttrs) bool

Escalates reports whether moving from `from` to `a` grants SUPERUSER or BYPASSRLS. Both let the role read every row of every table regardless of row-level security, so the UI guards the transition the way it guards a drop.

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).

func ListSessions

func ListSessions(ctx context.Context, p Pinger) ([]Session, error)

ListSessions lists client connections (except pgtower's own), active first, then by oldest.

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

func ListAllSettings(ctx context.Context, p Pinger) ([]Setting, error)

ListAllSettings returns every GUC from pg_settings, ordered by name.

func (Setting) Changeable

func (s Setting) Changeable() bool

Changeable reports whether the GUC can be changed at all (internal settings are compile-time and cannot).

func (Setting) NeedsRestart

func (s Setting) NeedsRestart() bool

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.

func ListTables

func ListTables(ctx context.Context, p Pinger) ([]Table, error)

ListTables lists tables (ordinary and partitioned) from user schemas, ordered by total size (heap + indexes + toast).

type TableDescription

type TableDescription struct {
	Schema      string
	Table       string
	Columns     []ColumnDef
	Indexes     []IndexDef
	Constraints []ConstraintDef
}

TableDescription is the "\d" of a table.

func DescribeTable

func DescribeTable(ctx context.Context, p Pinger, schema, table string) (TableDescription, error)

DescribeTable returns the columns, indexes and constraints of a table.

type TablePriv

type TablePriv struct {
	Privilege string
	Count     int
}

TablePriv is a table privilege and how many tables in the schema carry it.

type TuningInput

type TuningInput struct {
	RAMBytes       int64
	CPUs           int
	MaxConnections int
	SharedBuffers  int64
	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

type TuningRec struct {
	Name        string
	Current     string
	Recommended string
	Verdict     Verdict
	Note        string
}

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.

type Verdict

type Verdict string

Verdict rates a setting against its recommendation.

const (
	VerdictOK   Verdict = "ok"
	VerdictWarn Verdict = "warn"
	VerdictInfo Verdict = "info"
)

Jump to

Keyboard shortcuts

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