157 lines
5.3 KiB
Go
157 lines
5.3 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"path"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/stdlib"
|
|
"github.com/pressly/goose/v3"
|
|
"github.com/pressly/goose/v3/lock"
|
|
)
|
|
|
|
const (
|
|
// The session advisory lock is retried once per second for up to five
|
|
// minutes, so instances that start together apply migrations one at a time.
|
|
migrationLockRetryPeriodSeconds = 1
|
|
migrationLockRetryAttempts = 300
|
|
|
|
// migrationLockTimeout makes a DDL statement fail fast instead of queueing
|
|
// behind long transactions while it blocks every later query on the table.
|
|
migrationLockTimeout = 10 * time.Second
|
|
// migrationStatementTimeout bounds one migration statement. It stays below
|
|
// the five-minute startup limit so a slow statement reports its own error.
|
|
migrationStatementTimeout = 4 * time.Minute
|
|
)
|
|
|
|
// ErrNoMigrationToRollBack reports that no applied migration is left.
|
|
var ErrNoMigrationToRollBack = errors.New("no applied migration to roll back")
|
|
|
|
// MigrationResult describes one applied or rolled back migration.
|
|
type MigrationResult struct {
|
|
Version int64
|
|
Name string
|
|
Duration time.Duration
|
|
}
|
|
|
|
// MigrationStatus describes one known migration.
|
|
type MigrationStatus struct {
|
|
Version int64
|
|
Name string
|
|
Applied bool
|
|
AppliedAt time.Time
|
|
}
|
|
|
|
// Migrator applies goose SQL migrations through database/sql with the pgx
|
|
// driver. A PostgreSQL session advisory lock serializes concurrent runs.
|
|
type Migrator struct {
|
|
provider *goose.Provider
|
|
}
|
|
|
|
// NewMigrator does not connect until a migration operation runs. The caller
|
|
// must call Close.
|
|
func NewMigrator(databaseURL string, migrations fs.FS) (*Migrator, error) {
|
|
connConfig, err := migrationConnConfig(databaseURL)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
locker, err := lock.NewPostgresSessionLocker(
|
|
lock.WithLockTimeout(migrationLockRetryPeriodSeconds, migrationLockRetryAttempts),
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("postgres.NewMigrator - create session locker: %w", err)
|
|
}
|
|
database := stdlib.OpenDB(*connConfig)
|
|
provider, err := goose.NewProvider(goose.DialectPostgres, database, migrations,
|
|
goose.WithSessionLocker(locker),
|
|
goose.WithDisableGlobalRegistry(true),
|
|
)
|
|
if err != nil {
|
|
err = fmt.Errorf("postgres.NewMigrator - load migrations: %w", err)
|
|
if closeErr := database.Close(); closeErr != nil {
|
|
err = errors.Join(err, fmt.Errorf("postgres.NewMigrator - close migration database: %w", closeErr))
|
|
}
|
|
return nil, err
|
|
}
|
|
return &Migrator{provider: provider}, nil
|
|
}
|
|
|
|
// migrationConnConfig parses databaseURL and sets session timeouts for every
|
|
// migration connection.
|
|
func migrationConnConfig(databaseURL string) (*pgx.ConnConfig, error) {
|
|
connConfig, err := pgx.ParseConfig(databaseURL)
|
|
if err != nil {
|
|
// pgx redacts passwords only on a best-effort basis, so the parse error
|
|
// is not wrapped to keep the connection string out of logs.
|
|
return nil, errors.New("postgres.migrationConnConfig - DATABASE_URL is not a valid PostgreSQL connection string")
|
|
}
|
|
connConfig.RuntimeParams["lock_timeout"] = strconv.FormatInt(migrationLockTimeout.Milliseconds(), 10)
|
|
connConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(migrationStatementTimeout.Milliseconds(), 10)
|
|
return connConfig, nil
|
|
}
|
|
|
|
// Up applies every pending migration and returns them in order.
|
|
func (migrator *Migrator) Up(ctx context.Context) ([]MigrationResult, error) {
|
|
results, err := migrator.provider.Up(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Migrator.Up - apply migrations: %w", sanitizeConnectError(err))
|
|
}
|
|
applied := make([]MigrationResult, 0, len(results))
|
|
for _, result := range results {
|
|
applied = append(applied, newMigrationResult(result))
|
|
}
|
|
return applied, nil
|
|
}
|
|
|
|
// DownOne rolls back the most recently applied migration. It returns
|
|
// ErrNoMigrationToRollBack when the schema is already at version zero.
|
|
func (migrator *Migrator) DownOne(ctx context.Context) (MigrationResult, error) {
|
|
result, err := migrator.provider.Down(ctx)
|
|
if errors.Is(err, goose.ErrNoNextVersion) {
|
|
return MigrationResult{}, fmt.Errorf("Migrator.DownOne - roll back migration: %w", ErrNoMigrationToRollBack)
|
|
}
|
|
if err != nil {
|
|
return MigrationResult{}, fmt.Errorf("Migrator.DownOne - roll back migration: %w", sanitizeConnectError(err))
|
|
}
|
|
return newMigrationResult(result), nil
|
|
}
|
|
|
|
// Status lists every embedded migration with its database state.
|
|
func (migrator *Migrator) Status(ctx context.Context) ([]MigrationStatus, error) {
|
|
statuses, err := migrator.provider.Status(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Migrator.Status - read migration status: %w", sanitizeConnectError(err))
|
|
}
|
|
result := make([]MigrationStatus, 0, len(statuses))
|
|
for _, status := range statuses {
|
|
result = append(result, MigrationStatus{
|
|
Version: status.Source.Version,
|
|
Name: path.Base(status.Source.Path),
|
|
Applied: status.State == goose.StateApplied,
|
|
AppliedAt: status.AppliedAt,
|
|
})
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// Close releases the migration connections.
|
|
func (migrator *Migrator) Close() error {
|
|
if err := migrator.provider.Close(); err != nil {
|
|
return fmt.Errorf("Migrator.Close - close migration database: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func newMigrationResult(result *goose.MigrationResult) MigrationResult {
|
|
return MigrationResult{
|
|
Version: result.Source.Version,
|
|
Name: path.Base(result.Source.Path),
|
|
Duration: result.Duration,
|
|
}
|
|
}
|