2022-04-01 16:02:58 +02:00
|
|
|
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 {
|
2022-10-15 21:54:11 +02:00
|
|
|
return status, fmt.Errorf("migrate: no database connection")
|
2022-04-01 16:02:58 +02:00
|
|
|
}
|
|
|
|
|
2022-10-15 21:54:11 +02:00
|
|
|
// Get SQL dialect name.
|
2022-04-01 16:02:58 +02:00
|
|
|
name := db.Dialect().GetName()
|
|
|
|
|
|
|
|
if name == "" {
|
2022-10-15 21:54:11 +02:00
|
|
|
return status, fmt.Errorf("migrate: failed to determine sql dialect")
|
2022-04-01 16:02:58 +02:00
|
|
|
}
|
|
|
|
|
2022-10-15 21:54:11 +02:00
|
|
|
// Make sure a "migrations" table exists.
|
|
|
|
once[name].Do(func() {
|
|
|
|
err = db.AutoMigrate(&Migration{}).Error
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
2022-04-01 16:02:58 +02:00
|
|
|
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.
|
2022-10-15 21:54:11 +02:00
|
|
|
executed := Existing(db, "")
|
2022-04-01 16:02:58 +02:00
|
|
|
|
|
|
|
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?
|
2022-10-15 21:54:11 +02:00
|
|
|
if done, known := executed[migration.ID]; known {
|
2022-04-01 16:02:58 +02:00
|
|
|
migration.Dialect = done.Dialect
|
2022-10-15 21:54:11 +02:00
|
|
|
migration.Stage = done.Stage
|
2022-04-01 16:02:58 +02:00
|
|
|
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
|
|
|
|
}
|