Document every package and exported identifier, return the log level from NewLogger instead of keeping it in a package variable, and stop tests from mutating the argon2 parameters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
85 lines
2.2 KiB
Go
85 lines
2.2 KiB
Go
// Package migrations embeds the SQL schema migrations and applies them with
|
|
// goose.
|
|
package migrations
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"embed"
|
|
"fmt"
|
|
"io/fs"
|
|
|
|
_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" database/sql driver
|
|
"github.com/pressly/goose/v3"
|
|
"github.com/pressly/goose/v3/lock"
|
|
)
|
|
|
|
//go:embed sql/*.sql
|
|
var files embed.FS
|
|
|
|
// lockID is shared by every replica so concurrent "migrate up" calls during
|
|
// a rolling deploy serialize instead of racing.
|
|
const lockID = 0x7570746d
|
|
|
|
func newProvider(dsn string) (*goose.Provider, *sql.DB, error) {
|
|
db, err := sql.Open("pgx", dsn)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
sub, err := fs.Sub(files, "sql")
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
locker, err := lock.NewPostgresSessionLocker(lock.WithLockID(lockID))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
p, err := goose.NewProvider(goose.DialectPostgres, db, sub, goose.WithSessionLocker(locker))
|
|
if err != nil {
|
|
_ = db.Close()
|
|
return nil, nil, err
|
|
}
|
|
return p, db, nil
|
|
}
|
|
|
|
// Up applies all pending migrations.
|
|
func Up(ctx context.Context, dsn string) ([]*goose.MigrationResult, error) {
|
|
p, db, err := newProvider(dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("migrate: %w", err)
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
return p.Up(ctx)
|
|
}
|
|
|
|
// Down rolls back the most recent migration.
|
|
func Down(ctx context.Context, dsn string) (*goose.MigrationResult, error) {
|
|
p, db, err := newProvider(dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("migrate: %w", err)
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
return p.Down(ctx)
|
|
}
|
|
|
|
// Status lists every migration with its applied state.
|
|
func Status(ctx context.Context, dsn string) ([]*goose.MigrationStatus, error) {
|
|
p, db, err := newProvider(dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("migrate: %w", err)
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
return p.Status(ctx)
|
|
}
|
|
|
|
// Pending reports whether the database lags behind the embedded migrations;
|
|
// services refuse to start in that case instead of running against an old schema.
|
|
func Pending(ctx context.Context, dsn string) (bool, error) {
|
|
p, db, err := newProvider(dsn)
|
|
if err != nil {
|
|
return false, fmt.Errorf("migrate: %w", err)
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
return p.HasPending(ctx)
|
|
}
|