From 5f9b6b632d39fa97f6d36a7f0abfc85c4e5266c4 Mon Sep 17 00:00:00 2001 From: Deluan Date: Sat, 27 Jan 2024 19:44:49 -0500 Subject: [PATCH] Add a "upgrading schema" log message to the DB initialization when there are pending migrations. --- db/db.go | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/db/db.go b/db/db.go index cea44974..b1621401 100644 --- a/db/db.go +++ b/db/db.go @@ -60,19 +60,46 @@ func Init() { } gooseLogger := &logAdapter{silent: isSchemaEmpty(db)} - goose.SetLogger(gooseLogger) goose.SetBaseFS(embedMigrations) err = goose.SetDialect(Driver) if err != nil { log.Fatal("Invalid DB driver", "driver", Driver, err) } + if !isSchemaEmpty(db) && hasPendingMigrations(db, migrationsFolder) { + log.Info("Upgrading DB Schema to latest version") + } + goose.SetLogger(gooseLogger) err = goose.Up(db, migrationsFolder) if err != nil { log.Fatal("Failed to apply new migrations", err) } } +type statusLogger struct{ numPending int } + +func (*statusLogger) Fatalf(format string, v ...interface{}) { log.Fatal(fmt.Sprintf(format, v...)) } +func (l *statusLogger) Printf(format string, v ...interface{}) { + if len(v) < 1 { + return + } + if v0, ok := v[0].(string); !ok { + return + } else if v0 == "Pending" { + l.numPending++ + } +} + +func hasPendingMigrations(db *sql.DB, folder string) bool { + l := &statusLogger{} + goose.SetLogger(l) + err := goose.Status(db, folder) + if err != nil { + log.Fatal("Failed to check for pending migrations", err) + } + return l.numPending > 0 +} + func isSchemaEmpty(db *sql.DB) bool { rows, err := db.Query("SELECT name FROM sqlite_master WHERE type='table' AND name='goose_db_version';") // nolint:rowserrcheck if err != nil {