pgbackup

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: GPL-3.0, LGPL-3.0 Imports: 23 Imported by: ? 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.

README

pgbackup

GoDoc codecov CI GitHub License

Embeddable Go library for backing up and restoring PostgreSQL backups to and from S3. Backs up with pg_dump and restores with psql or pg_restore.

Caveats

pgbackup shells out to the PostgreSQL client tools: pg_dump, pg_dumpall, psql, and pg_restore. They must be on PATH at runtime. The recommended way to run pgbackup is inside an official postgres: image as it ships the matching client tools and guarantees version alignment with the server you're backing up.

Example

package main

import (
	"context"
	"log"
	"log/slog"
	"os"
	"time"

	"github.com/kamikazechaser/pgbackup"
)

func main() {
	ctx := context.Background()

	b, err := pgbackup.New(
		[]pgbackup.Target{
			{
				// A normal single-database backup.
				Name: "app",
				DSN:  "host=db user=pg password=secret dbname=app sslmode=require",
			},
			{
				// A second target can use its own database and codec.
				Name:        "analytics",
				DSN:         "host=db user=pg password=secret dbname=analytics sslmode=require",
				Compression: pgbackup.Gzip,
			},
			{
				// AllDatabases uses pg_dumpall for cluster-wide dumps.
				Name:         "globals",
				DSN:          "host=db user=pg password=secret sslmode=require",
				AllDatabases: true,
			},
		},
		pgbackup.S3Config{
			Bucket:    "my-backups",
			Region:    "us-east-1",
			Prefix:    "nightly/",
			AccessKey: "",
			SecretKey: "",
		},
		pgbackup.Options{
			Compression: pgbackup.Zstd,
			MaxParallel: 2,
			// Logger is optional. If nil, pgbackup uses slog's default text logger.
			Logger: slog.New(slog.NewTextHandler(os.Stderr, nil)),
			// After each successful backup, pgbackup sweeps that target's prefix.
			// It keeps the newest 7 backups, then deletes the rest once older than 30 days.
			Retention: &pgbackup.Retention{
				KeepLast:  7,
				OlderThan: 30 * 24 * time.Hour,
			},
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	// Run all targets once. Call this from your scheduler.
	// Each successful target backup also runs its retention sweep.
	for _, result := range b.BackupAll(ctx) {
		if result.Err != nil {
			log.Printf("backup %s failed: %v", result.Target, result.Err)
			continue
		}
		log.Printf("backup %s written to s3://%s/%s", result.Target, result.Bucket, result.Key)
	}

	// Restore the newest app backup into the configured app target.
	restore, err := b.RestoreLatest(ctx, "app", pgbackup.RestoreOptions{})
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("restored %s with %s", restore.Key, restore.Tool)
}

License

LGPL-3.0.

Documentation

Overview

Package pgbackup backs up Postgres databases to S3.

It runs pg_dump (or pg_dumpall for a whole cluster), compresses the stream, and uploads it to S3 as a multipart upload using a bounded in-memory buffer. There is no scheduler: call Backup or BackupAll from whatever drives your schedule (cron, a systemd timer, a k8s CronJob, a ticker).

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrObjectNotFound = errors.New("pgbackup: object not found")
)

ErrObjectNotFound is returned when an object key does not exist.

Functions

func ValidateTarget

func ValidateTarget(t Target) error

ValidateTarget applies the same per-target checks New performs: name present and key-safe, DSN and discrete connection fields not mixed, AllDatabases not combined with Tables, ExcludeTables, or a non-plain Format, and Format being plain or custom. It does not check uniqueness across a set. Use it to filter a dynamic target set before constructing a Backupper, or let Runner apply it.

Types

type Backupper

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

Backupper runs backups and restores against a fixed set of targets.

func New

func New(targets []Target, s3 S3Config, opts Options) (*Backupper, error)

New validates the configuration and returns a Backupper. It starts no goroutines.

It checks that Names are unique and key-safe, that DSN and the discrete connection fields are not mixed, that AllDatabases is not combined with Tables, ExcludeTables or a non-plain Format, that Format is plain or custom, and that Retention.KeepLast is at least 1 when OlderThan is set.

func (*Backupper) Backup

func (b *Backupper) Backup(ctx context.Context, name string) (*Result, error)

Backup runs one target and returns its result.

The stream is piped from pg_dump through a compressor into the S3 uploader via an io.Pipe. If pg_dump fails, the error is pushed into the pipe before EOF, so the upload aborts and leaves no partial object.

func (*Backupper) BackupAll

func (b *Backupper) BackupAll(ctx context.Context) []*Result

BackupAll runs every target concurrently, bounded by MaxParallel, and returns one Result per target when all finish. A failure in one target does not cancel the others: errgroup is used only for its semaphore, and the per-target function never returns an error.

func (*Backupper) Restore

func (b *Backupper) Restore(ctx context.Context, name string, opts RestoreOptions) (*RestoreResult, error)

Restore downloads the backup named by opts.Key (or the newest backup of name when opts.Latest is set) and loads it into the destination.

func (*Backupper) RestoreLatest

func (b *Backupper) RestoreLatest(ctx context.Context, name string, opts RestoreOptions) (*RestoreResult, error)

RestoreLatest is shorthand for Restore with Latest=true.

type Compression

type Compression string

Compression selects the codec applied to a dump stream.

const (
	// None disables compression.
	None Compression = "none"
	// Gzip uses the standard library's compress/gzip.
	Gzip Compression = "gzip"
	// Zstd is the default codec for plain dumps.
	Zstd Compression = "zstd"
)

type Logger

type Logger interface {
	Info(msg string, args ...any)
	Error(msg string, args ...any)
}

Logger is the logging interface the library uses. Provide your own, or leave Options.Logger nil for the default slog.Logger.

type Options

type Options struct {
	Compression      Compression
	CompressionLevel int
	ObjectKeyFunc    func(t Target, ts time.Time, ext string) string
	TempDir          string
	Logger           Logger
	MaxParallel      int
	Retention        *Retention
}

Options are Backupper-wide defaults.

type RestoreOptions

type RestoreOptions struct {
	// Source. Exactly one should be set. If both are zero, Latest is implied.
	// Key is a specific object key.
	Key string
	// Latest picks the newest object under the target's prefix.
	Latest bool

	// Into is the destination. nil restores into the target's own DSN.
	Into *Target

	// SingleTransaction wraps the restore in a single transaction. Nil picks
	// by format: true for a single plain restore, false for an all-databases
	// restore. Setting it true on an all-databases restore is an error.
	SingleTransaction *bool
	// StopOnError maps to psql's ON_ERROR_STOP=1 or pg_restore's
	// --exit-on-error. Nil means true.
	StopOnError *bool
	// PreDropDatabase drops and recreates the destination database before
	// restoring. It is destructive and requires Confirm.
	PreDropDatabase bool
	// Confirm must be "drop " plus the destination database name, and gates
	// PreDropDatabase.
	Confirm string
	// Force uses DROP DATABASE WITH (FORCE), available on Postgres 13 and
	// later.
	Force bool
	// Echo echoes every statement the client runs.
	Echo bool
	// DryRun downloads and decompresses the object but discards the output
	// instead of restoring. It works even when built with -tags nopgtools.
	DryRun bool
	// ExtraArgs are passed verbatim to psql or pg_restore.
	ExtraArgs []string
}

RestoreOptions controls a single restore run. Restore is destructive, so every field defaults to the safe choice and must be explicitly enabled.

type RestoreResult

type RestoreResult struct {
	Target string
	// Into is the DSN that received the restore, with the password redacted.
	Into      string
	Bucket    string
	Key       string
	Bytes     int64
	Duration  time.Duration
	StartedAt time.Time
	// Tool is "psql" or "pg_restore".
	Tool string
	Err  error
}

RestoreResult describes one restore outcome.

type Result

type Result struct {
	Target      string
	Bucket, Key string
	Bytes       int64
	Duration    time.Duration
	StartedAt   time.Time
	Err         error
}

Result describes one target's backup outcome.

type Retention

type Retention struct {
	// KeepLast is the number of newest objects always kept, regardless of
	// OlderThan.
	KeepLast int
	// OlderThan deletes objects older than this duration, after KeepLast is
	// honored. Zero disables age-based deletion.
	OlderThan time.Duration
}

Retention governs cleanup after each backup. Sweeps are scoped to one target's prefix, so they never touch another target's objects.

type Runner

type Runner struct {
	Source Source
	S3     S3Config
	Opts   Options

	// OnInvalid, when non-nil, is called for each target that fails
	// ValidateTarget. Such targets are skipped and Run continues with the
	// rest. When nil, the first invalid target makes Run return an error.
	OnInvalid func(Target, error)
}

Runner fetches targets from a Source on each run and backs them up. It is a convenience over New + BackupAll: every Run rebuilds a Backupper from the freshly fetched targets, so dynamic inventories need no changes to the core API. Like Backupper, it starts no goroutines and has no scheduler.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context) ([]*Result, error)

Run fetches the current targets from Source, filters invalid ones (if OnInvalid is set), builds a Backupper, and backs up every target. Returns one Result per target, identical in shape to Backupper.BackupAll.

Uniqueness of target names is enforced by New; duplicates from the Source cause Run to return an error. Deduplicate in Fetch if your inventory may contain them.

type S3Config

type S3Config struct {
	Bucket string
	// Region is the AWS region. Use "auto" for Cloudflare R2.
	Region string
	// Endpoint is an alternate S3-compatible endpoint, such as R2 or MinIO.
	Endpoint string
	// PathStyle enables path-style addressing. nil leaves the SDK default.
	PathStyle *bool
	// AccessKey is optional. Empty uses the default credential chain.
	AccessKey string
	SecretKey string
	// SessionToken is optional for temporary credentials.
	SessionToken string
	// Prefix is the object key prefix. Empty uses "pgbackup/".
	Prefix string
	// StorageClass is an S3 storage class such as "STANDARD_IA". Empty leaves
	// the bucket default.
	StorageClass string
	// PartSize is the multipart part size. Empty uses 16 MiB.
	PartSize int64

	// ServerSideEncryption is "AES256" for SSE-S3 or "aws:kms" for SSE-KMS.
	ServerSideEncryption string
	// SSEKMSKeyID is the KMS key ARN/id when ServerSideEncryption is "aws:kms".
	SSEKMSKeyID string

	// UploadTimeout bounds a single upload. Zero means no timeout.
	UploadTimeout time.Duration
}

S3Config is the upload destination. It works with AWS S3, R2, MinIO, B2 and Spaces.

type Source

type Source interface {
	Fetch(ctx context.Context) ([]Target, error)
}

Source produces the current set of backup targets. Implement it against whatever holds your inventory: a SQL database, Redis, an HTTP API, a file, anything. Fetch is called once per backup run, so targets added or removed between runs are reflected automatically. Fetch must return the complete current set; sources that need pagination handle it internally.

type Target

type Target struct {
	// Name identifies the target and becomes part of the S3 object key.
	// It must be unique across all targets and contain only [A-Za-z0-9._-]
	// (no slash, no "..").
	Name string

	// DSN is a libpq conninfo or a postgresql:// URI. Leave it empty to
	// build one from the discrete fields below.
	DSN string

	// Host, Port, User, Password, Database and SSLMode build a conninfo
	// when DSN is empty. They cannot be combined with DSN.
	Host, Port, User, Password, Database, SSLMode string

	// AllDatabases uses pg_dumpall to dump every database plus globals and
	// roles. The output is always plain SQL.
	AllDatabases bool

	// Tables and ExcludeTables add --table and --exclude-table flags. They
	// cannot be used with AllDatabases.
	Tables []string
	// ExcludeTables adds --exclude-table flags. See Tables.
	ExcludeTables []string

	// Format is "plain" (the default, restored with psql) or "custom" (the
	// -Fc format, restored with pg_restore).
	Format string

	// ExtraArgs are passed verbatim to pg_dump, e.g. "--no-owner".
	ExtraArgs []string

	// Compression overrides Options.Compression for this target. Zero
	// falls back to the default: zstd for plain, none for custom.
	Compression Compression
}

Target describes one Postgres database to back up.

Either set DSN (a libpq conninfo or a postgresql:// URI) or fill in the discrete fields below and let New assemble them into a conninfo. Mixing the two is an error. The password is moved into a child-scoped PGPASSWORD environment variable and stripped from argv, so it does not appear in ps.

Jump to

Keyboard shortcuts

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