2022-05-11 22:47:31 +00:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2023-05-26 01:04:43 +00:00
|
|
|
"net/url"
|
2022-05-11 22:47:31 +00:00
|
|
|
|
|
|
|
"npm/embed"
|
2023-05-26 01:04:43 +00:00
|
|
|
"npm/internal/config"
|
2022-05-11 22:47:31 +00:00
|
|
|
"npm/internal/logger"
|
|
|
|
|
2023-05-26 01:04:43 +00:00
|
|
|
"github.com/amacneil/dbmate/v2/pkg/dbmate"
|
|
|
|
_ "github.com/amacneil/dbmate/v2/pkg/driver/postgres"
|
|
|
|
_ "github.com/amacneil/dbmate/v2/pkg/driver/sqlite"
|
2022-05-11 22:47:31 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type afterMigrationComplete func()
|
|
|
|
|
2023-05-26 01:04:43 +00:00
|
|
|
// Migrate will bring the db up to date
|
2022-05-11 22:47:31 +00:00
|
|
|
func Migrate(followup afterMigrationComplete) bool {
|
2023-05-26 01:04:43 +00:00
|
|
|
dbURL := config.Configuration.DB.GetDBMateConnectURL()
|
|
|
|
u, _ := url.Parse(dbURL)
|
|
|
|
db := dbmate.New(u)
|
|
|
|
db.FS = embed.MigrationFiles
|
|
|
|
db.MigrationsDir = []string{fmt.Sprintf("./migrations/%s", config.Configuration.DB.GetDriver())}
|
2022-05-11 22:47:31 +00:00
|
|
|
|
2023-05-26 01:04:43 +00:00
|
|
|
migrations, err := db.FindMigrations()
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("MigrationError", err)
|
2022-05-11 22:47:31 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2023-05-26 01:04:43 +00:00
|
|
|
for _, m := range migrations {
|
|
|
|
logger.Debug("%s: %s", m.Version, m.FilePath)
|
2022-05-11 22:47:31 +00:00
|
|
|
}
|
|
|
|
|
2023-05-26 01:04:43 +00:00
|
|
|
err = db.CreateAndMigrate()
|
2022-05-11 22:47:31 +00:00
|
|
|
if err != nil {
|
2023-05-26 01:04:43 +00:00
|
|
|
logger.Error("MigrationError", err)
|
|
|
|
return false
|
2022-05-11 22:47:31 +00:00
|
|
|
}
|
|
|
|
|
2023-05-26 01:04:43 +00:00
|
|
|
followup()
|
|
|
|
return true
|
2022-05-11 22:47:31 +00:00
|
|
|
}
|