43 lines
1.2 KiB
Go
43 lines
1.2 KiB
Go
// Package migrate provides a small embedded-filesystem wrapper around Goose.
|
|
// Applications still own their SQL files and migration policy.
|
|
package migrate
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"io/fs"
|
|
|
|
_ "github.com/jackc/pgx/v5/stdlib"
|
|
"github.com/pressly/goose/v3"
|
|
)
|
|
|
|
// Up applies all pending PostgreSQL migrations in migrationsFS/dir. The
|
|
// filesystem is normally an embed.FS supplied by the consuming application.
|
|
func Up(ctx context.Context, databaseURL string, migrationsFS fs.FS, dir string) error {
|
|
if databaseURL == "" {
|
|
return fmt.Errorf("database URL is required")
|
|
}
|
|
if migrationsFS == nil {
|
|
return fmt.Errorf("migration filesystem is required")
|
|
}
|
|
|
|
db, err := sql.Open("pgx", databaseURL)
|
|
if err != nil {
|
|
return fmt.Errorf("open migration database: %w", err)
|
|
}
|
|
defer db.Close()
|
|
if err := db.PingContext(ctx); err != nil {
|
|
return fmt.Errorf("ping migration database: %w", err)
|
|
}
|
|
|
|
goose.SetBaseFS(migrationsFS)
|
|
if err := goose.SetDialect("postgres"); err != nil {
|
|
return fmt.Errorf("set migration dialect: %w", err)
|
|
}
|
|
if err := goose.UpContext(ctx, db, dir); err != nil {
|
|
return fmt.Errorf("run migrations: %w", err)
|
|
}
|
|
return nil
|
|
}
|