Files
minstrel/internal/db/db.go
T
bvandeusenandClaude Opus 5.5 7491a7b60f test: migrations round-trip down and up; dbtest fails when the lane has no database (#8509, #8510)
Migration round trip (family idea "Migration CI lane"):
- TestMigrationsRoundTrip, in the integration lane, migrates a scratch
  database to the baseline, then all the way up, then every migration
  after the baseline down, then up again.
- The schema after the down pass must match a database migrated to the
  baseline alone: columns, indexes, constraints, sequences, enums,
  functions and triggers. So a down file that leaves something behind
  fails, as well as one that errors.
- The baseline's own down file refuses to run by design, so the round
  trip stops there.
- The test uses golang-migrate as a library, with no migrator binary.
- The scratch database is dropped afterwards, and the shared test
  database is never migrated down.

dbtest (family idea "dbtest Pool and Fixtures"):
- dbtest.URL skips without a database. It fails instead when
  MINSTREL_TEST_DATABASE_REQUIRED is set, and the integration lane sets
  it.
- dbtest.On(t, db) gives One/Exec/Count fixtures. The local copies are
  repointed to them: exec in api, mustExec/mustID in backup,
  countQueueRows in scrobble, and countTrackSim/countArtistSim in
  similarity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:44:18 -05:00

87 lines
2.5 KiB
Go

package db
import (
"context"
"embed"
"errors"
"fmt"
"log/slog"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/pgx/v5"
"github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/jackc/pgx/v5/pgxpool"
)
//go:embed migrations/*.sql
var migrationsFS embed.FS
// Open establishes a pgx connection pool. The caller owns the returned pool
// and must Close() it on shutdown.
func Open(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
if dsn == "" {
return nil, errors.New("db: database URL is empty")
}
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
return nil, fmt.Errorf("db: create pool: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("db: ping: %w", err)
}
return pool, nil
}
// Migrate applies any pending migrations embedded in this package. It is safe
// to call concurrently with application traffic only if the database is idle;
// in practice this runs once at startup before the HTTP server binds.
func Migrate(dsn string, logger *slog.Logger) error {
m, err := newMigrator(dsn)
if err != nil {
return err
}
defer func() {
if srcErr, dbErr := m.Close(); srcErr != nil || dbErr != nil {
logger.Warn("migrate close", "src_err", srcErr, "db_err", dbErr)
}
}()
if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
return fmt.Errorf("db: migrate up: %w", err)
}
version, dirty, verr := m.Version()
if verr != nil && !errors.Is(verr, migrate.ErrNilVersion) {
return fmt.Errorf("db: migrate version: %w", verr)
}
logger.Info("migrations applied", "version", version, "dirty", dirty)
return nil
}
// newMigrator opens the embedded migrations against dsn. The caller closes it.
func newMigrator(dsn string) (*migrate.Migrate, error) {
if dsn == "" {
return nil, errors.New("db: database URL is empty")
}
src, err := iofs.New(migrationsFS, "migrations")
if err != nil {
return nil, fmt.Errorf("db: iofs source: %w", err)
}
m, err := migrate.NewWithSourceInstance("iofs", src, "pgx5://"+trimScheme(dsn))
if err != nil {
return nil, fmt.Errorf("db: migrate init: %w", err)
}
return m, nil
}
// trimScheme rewrites a postgres://... or postgresql://... DSN to the bare
// form expected by the migrate pgx driver (it registers its own scheme).
func trimScheme(dsn string) string {
for _, prefix := range []string{"postgres://", "postgresql://"} {
if len(dsn) > len(prefix) && dsn[:len(prefix)] == prefix {
return dsn[len(prefix):]
}
}
return dsn
}