Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/add migration list subcommand #2012

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions cmd/migrate/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func AddMigrateCommand(a *cli.App) *cobra.Command {
cmd.AddCommand(addUpCommand())
cmd.AddCommand(addDownCommand())
cmd.AddCommand(addCreateCommand())
cmd.AddCommand(addListCommand())

return cmd
}
Expand Down Expand Up @@ -125,3 +126,45 @@ func addCreateCommand() *cobra.Command {

return cmd
}

func addListCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "list all migrations",
Annotations: map[string]string{
"CheckMigration": "false",
"ShouldBootstrap": "false",
},
Run: func(cmd *cobra.Command, args []string) {
cfg, err := config.Get()
if err != nil {
log.WithError(err).Fatalf("Error fetching the config.")
}

db, err := postgres.NewDB(cfg)
if err != nil {
log.Fatal(err)
}

defer db.Close()

m := migrator.New(db)
migrationRecords, err := m.List()
if err != nil {
log.WithError(err).Fatal("failed to list migrations")
}

if len(migrationRecords) == 0 {
fmt.Println("No migrations found")
}

fmt.Printf("Name Applied At\n----------------- ----------------------------\n")

for _, record := range migrationRecords {
fmt.Printf("%s %v\n", record.Name, record.AppliedAt.Format("2006-01-02 15:04 (MST)"))
}
},
}

return cmd
}
25 changes: 25 additions & 0 deletions internal/pkg/migrator/migrator.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package migrator

import (
"time"

"github.com/frain-dev/convoy"
"github.com/frain-dev/convoy/database"
"github.com/jmoiron/sqlx"
Expand All @@ -11,6 +13,11 @@ var (
tableSchema = "convoy"
)

type MigrationRecord struct {
Name string
AppliedAt time.Time
}

type Migrator struct {
dbx *sqlx.DB
src migrate.MigrationSource
Expand Down Expand Up @@ -41,3 +48,21 @@ func (m *Migrator) Down(max int) error {
}
return nil
}

func (m *Migrator) List() ([]MigrationRecord, error) {
records, err := migrate.GetMigrationRecords(m.dbx.DB, "postgres")
if err != nil {
return nil, err
}

var migrationRecords []MigrationRecord
for _, record := range records {
migrationRecord := MigrationRecord{
Name: record.Id,
AppliedAt: record.AppliedAt,
}
migrationRecords = append(migrationRecords, migrationRecord)
}

return migrationRecords, nil
}