Use tern to perform migrations on startup

This commit is contained in:
Abhishek Shroff
2024-07-22 16:13:51 -07:00
parent ca56e77f0c
commit 2e4f8d0820
15 changed files with 215 additions and 36 deletions
+21 -1
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"github.com/jackc/pgx/v5"
"github.com/shroff/phylum/server/internal/migrations"
"github.com/sirupsen/logrus"
)
@@ -14,7 +15,7 @@ type DbHandler struct {
queries *Queries
}
func NewDb(dsn string, trace bool) (*DbHandler, error) {
func NewDb(dsn string, trace, autoMigrate bool) (*DbHandler, error) {
config, err := pgx.ParseConfig(dsn)
if err != nil {
return nil, errors.New("Unable to parse DSN: " + err.Error())
@@ -31,6 +32,25 @@ func NewDb(dsn string, trace bool) (*DbHandler, error) {
logrus.Info("Connected to " + config.Database + " at " + config.Host + ":" + fmt.Sprint(config.Port))
if migrator, err := migrations.NewMigrator(conn); err != nil {
panic(err)
} else {
version, err := migrator.GetCurrentVersion()
if err != nil {
panic(err)
}
latest := migrator.GetLatestVersion()
if version != latest {
if autoMigrate {
logrus.Info(fmt.Sprintf("Migrating database from version %d to %d", version, latest))
migrator.Migrate()
} else {
panic(fmt.Sprintf("Schema is not at latest version (current %d, latest %d)", version, latest))
}
}
}
return &DbHandler{
conn: conn,
queries: &Queries{db: conn},