status.go

 1package goose
 2
 3import (
 4	"context"
 5	"database/sql"
 6	"errors"
 7	"fmt"
 8	"path/filepath"
 9	"time"
10)
11
12// Status prints the status of all migrations.
13func Status(db *sql.DB, dir string, opts ...OptionsFunc) error {
14	ctx := context.Background()
15	return StatusContext(ctx, db, dir, opts...)
16}
17
18// StatusContext prints the status of all migrations.
19func StatusContext(ctx context.Context, db *sql.DB, dir string, opts ...OptionsFunc) error {
20	option := &options{}
21	for _, f := range opts {
22		f(option)
23	}
24	migrations, err := CollectMigrations(dir, minVersion, maxVersion)
25	if err != nil {
26		return fmt.Errorf("failed to collect migrations: %w", err)
27	}
28	if option.noVersioning {
29		log.Printf("    Applied At                  Migration")
30		log.Printf("    =======================================")
31		for _, current := range migrations {
32			log.Printf("    %-24s -- %v", "no versioning", filepath.Base(current.Source))
33		}
34		return nil
35	}
36
37	// must ensure that the version table exists if we're running on a pristine DB
38	if _, err := EnsureDBVersionContext(ctx, db); err != nil {
39		return fmt.Errorf("failed to ensure DB version: %w", err)
40	}
41
42	log.Printf("    Applied At                  Migration")
43	log.Printf("    =======================================")
44	for _, migration := range migrations {
45		if err := printMigrationStatus(ctx, db, migration.Version, filepath.Base(migration.Source)); err != nil {
46			return fmt.Errorf("failed to print status: %w", err)
47		}
48	}
49
50	return nil
51}
52
53func printMigrationStatus(ctx context.Context, db *sql.DB, version int64, script string) error {
54	m, err := store.GetMigration(ctx, db, TableName(), version)
55	if err != nil && !errors.Is(err, sql.ErrNoRows) {
56		return fmt.Errorf("failed to query the latest migration: %w", err)
57	}
58	appliedAt := "Pending"
59	if m != nil && m.IsApplied {
60		appliedAt = m.Timestamp.Format(time.ANSIC)
61	}
62	log.Printf("    %-24s -- %v", appliedAt, script)
63	return nil
64}