photoprism/internal/migrate/status.go
Michael Mayer a61470dfc7 Migrations: Implement "photoprism migrations ls" command #2216
Lists the status of migrations. Changed "migrate" to "migrations run".
2022-04-01 16:02:58 +02:00

65 lines
1.6 KiB
Go

package migrate
import (
"fmt"
"github.com/dustin/go-humanize/english"
"github.com/jinzhu/gorm"
"github.com/photoprism/photoprism/pkg/list"
)
// Status returns the current status of schema migrations.
func Status(db *gorm.DB, ids []string) (status Migrations, err error) {
status = Migrations{}
if db == nil {
return status, fmt.Errorf("migrate: database connection required")
}
name := db.Dialect().GetName()
if name == "" {
return status, fmt.Errorf("migrate: database has no dialect name")
}
if err := db.AutoMigrate(&Migration{}).Error; err != nil {
return status, fmt.Errorf("migrate: %s (create migrations table)", err)
}
migrations, ok := Dialects[name]
if !ok && len(migrations) == 0 {
return status, fmt.Errorf("migrate: no migrations found for %s", name)
}
// Find previously executed migrations.
executed := Existing(db)
if prev := len(executed); prev == 0 {
log.Infof("migrate: no previously executed migrations")
} else {
log.Debugf("migrate: found %s", english.Plural(len(executed), "previous migration", "previous migrations"))
}
for _, migration := range migrations {
// Excluded?
if list.Excludes(ids, migration.ID) {
continue
}
// Already executed?
if done, ok := executed[migration.ID]; ok {
migration.Dialect = done.Dialect
migration.Error = done.Error
migration.Source = done.Source
migration.StartedAt = done.StartedAt
migration.FinishedAt = done.FinishedAt
status = append(status, migration)
} else {
// Should not happen.
status = append(status, migration)
}
}
return status, nil
}