Files
archie/internal/platform/pg/pg.go
T

72 lines
2.0 KiB
Go

// Package pg opens Archie's Postgres connections and applies its one ordered
// migration series.
package pg
import (
"context"
"embed"
"errors"
"fmt"
"io/fs"
"log/slog"
// Registers the "pgx" database/sql driver that sqlx and goose use.
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/jmoiron/sqlx"
"github.com/pressly/goose/v3"
"github.com/pressly/goose/v3/lock"
)
//go:embed migrations
var migrationFiles embed.FS
// Open connects with the runtime URL and checks the connection.
func Open(ctx context.Context, url string) (*sqlx.DB, error) {
db, err := sqlx.Open("pgx", url)
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
if err := db.PingContext(ctx); err != nil {
_ = db.Close()
return nil, fmt.Errorf("reach database: %w", err)
}
return db, nil
}
// Migrate applies every pending migration as the owner, under a session
// advisory lock, so two instances starting together never race. A failed
// migration returns an error and the boot stops.
func Migrate(ctx context.Context, log *slog.Logger, ownerURL string) error {
db, err := Open(ctx, ownerURL)
if err != nil {
return fmt.Errorf("owner connection: %w", err)
}
defer func() { _ = db.Close() }()
files, err := fs.Sub(migrationFiles, "migrations")
if err != nil {
return fmt.Errorf("migration files: %w", err)
}
locker, err := lock.NewPostgresSessionLocker()
if err != nil {
return fmt.Errorf("migration lock: %w", err)
}
provider, err := goose.NewProvider(goose.DialectPostgres, db.DB, files, goose.WithSessionLocker(locker))
if errors.Is(err, goose.ErrNoMigrations) {
// The series is empty until the first module adds its schema.
log.InfoContext(ctx, "no migrations to apply")
return nil
}
if err != nil {
return fmt.Errorf("migration provider: %w", err)
}
results, err := provider.Up(ctx)
if err != nil {
return fmt.Errorf("apply migrations: %w", err)
}
for _, r := range results {
log.InfoContext(ctx, "migration applied", "version", r.Source.Version, "file", r.Source.Path, "took", r.Duration)
}
return nil
}