This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
initialize.go
77 lines (66 loc) · 2.02 KB
/
initialize.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package server
import (
"context"
"fmt"
"github.com/flyteorg/flyteadmin/pkg/repositories"
"github.com/flyteorg/flyteadmin/pkg/repositories/config"
"github.com/flyteorg/flyteadmin/pkg/runtime"
"github.com/flyteorg/flytestdlib/logger"
"github.com/go-gormigrate/gormigrate/v2"
"gorm.io/gorm"
)
func withDB(ctx context.Context, do func(db *gorm.DB) error) error {
configuration := runtime.NewConfigurationProvider()
databaseConfig := configuration.ApplicationConfiguration().GetDbConfig()
logConfig := logger.GetConfig()
db, err := repositories.GetDB(ctx, databaseConfig, logConfig)
if err != nil {
logger.Fatal(ctx, err)
}
sqlDB, err := db.DB()
if err != nil {
logger.Fatal(ctx, err)
}
defer func(deferCtx context.Context) {
if err = sqlDB.Close(); err != nil {
logger.Fatal(deferCtx, err)
}
}(ctx)
if err = sqlDB.Ping(); err != nil {
return err
}
return do(db)
}
// Migrate runs all configured migrations
func Migrate(ctx context.Context) error {
return withDB(ctx, func(db *gorm.DB) error {
m := gormigrate.New(db, gormigrate.DefaultOptions, config.Migrations)
if err := m.Migrate(); err != nil {
return fmt.Errorf("database migration failed: %v", err)
}
logger.Infof(ctx, "Migration ran successfully")
return nil
})
}
// Rollback rolls back the last migration
func Rollback(ctx context.Context) error {
return withDB(ctx, func(db *gorm.DB) error {
m := gormigrate.New(db, gormigrate.DefaultOptions, config.Migrations)
err := m.RollbackLast()
if err != nil {
return fmt.Errorf("could not rollback latest migration: %v", err)
}
logger.Infof(ctx, "Rolled back one migration successfully")
return nil
})
}
// SeedProjects creates a set of given projects in the DB
func SeedProjects(ctx context.Context, projects []string) error {
return withDB(ctx, func(db *gorm.DB) error {
if err := config.SeedProjects(db, projects); err != nil {
return fmt.Errorf("could not add projects to database with err: %v", err)
}
logger.Infof(ctx, "Successfully added projects to database")
return nil
})
}