-
Notifications
You must be signed in to change notification settings - Fork 351
/
migration.go
234 lines (214 loc) · 5.73 KB
/
migration.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package db
import (
"context"
"errors"
"fmt"
"os"
"time"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database"
"github.com/golang-migrate/migrate/v4/database/postgres"
"github.com/golang-migrate/migrate/v4/source"
"github.com/golang-migrate/migrate/v4/source/httpfs"
"github.com/rakyll/statik/fs"
"github.com/treeverse/lakefs/pkg/db/params"
"github.com/treeverse/lakefs/pkg/ddl"
"github.com/treeverse/lakefs/pkg/logging"
"gopkg.in/retry.v1"
)
var ErrSchemaNotCompatible = errors.New("db schema version not compatible with latest version")
type Migrator interface {
Migrate(ctx context.Context) error
}
type DatabaseMigrator struct {
params params.Database
}
func NewDatabaseMigrator(params params.Database) *DatabaseMigrator {
return &DatabaseMigrator{
params: params,
}
}
func (d *DatabaseMigrator) Migrate(ctx context.Context) error {
log := logging.FromContext(ctx)
start := time.Now()
lg := log.WithFields(logging.Fields{
"direction": "up",
})
err := MigrateUp(d.params)
if err != nil {
lg.WithError(err).Error("Failed to migrate")
return err
} else {
lg.WithField("took", time.Since(start)).Info("schema migrated")
}
return nil
}
func getStatikSrc() (source.Driver, error) {
// statik fs to our migrate source
migrationFs, err := fs.NewWithNamespace(ddl.Ddl)
if err != nil {
return nil, err
}
return httpfs.New(migrationFs, "/")
}
func ValidateSchemaUpToDate(ctx context.Context, dbPool Database, params params.Database) error {
version, _, err := MigrateVersion(ctx, dbPool, params)
if err != nil {
return err
}
available, err := GetLastMigrationAvailable()
if err != nil {
return err
}
if available != version {
return fmt.Errorf("%w: db version=%d, available=%d", ErrSchemaNotCompatible, version, available)
}
return nil
}
func GetLastMigrationAvailable() (uint, error) {
src, err := getStatikSrc()
if err != nil {
return 0, err
}
defer func() {
_ = src.Close()
}()
current, err := src.First()
if err != nil {
return 0, fmt.Errorf("%w: failed to find first migration", err)
}
for {
next, err := src.Next(current)
if errors.Is(err, os.ErrNotExist) {
return current, nil
}
if err != nil {
return 0, err
}
current = next
}
}
func getMigrate(params params.Database) (*migrate.Migrate, error) {
src, err := getStatikSrc()
if err != nil {
return nil, err
}
defer func() {
_ = src.Close()
}()
connectionString := params.ConnectionString
m, err := tryNewWithSourceInstance("httpfs", src, connectionString)
if err != nil {
return nil, err
}
return m, nil
}
// getMigrateDatabaseDriver returns a database name and a (migrate)
// database.Driver for use in migration. Use it to prevent
// migrate.NewWithSourceInstance from applying defaults when databaseURL is
// empty -- those defaults will be different from the ones in pg/pgx.
func getMigrateDatabaseDriver(databaseURL string) (string, database.Driver, error) {
driver, err := (&postgres.Postgres{}).Open(databaseURL)
return "postgres", driver, err
}
func tryNewWithSourceInstance(sourceName string, sourceInstance source.Driver, databaseURL string) (*migrate.Migrate, error) {
strategy := params.DatabaseRetryStrategy
var m *migrate.Migrate
var err error
for a := retry.Start(strategy, nil); a.Next(); {
var (
dbName string
dbDriver database.Driver
)
dbName, dbDriver, err = getMigrateDatabaseDriver(databaseURL)
if err != nil {
return nil, fmt.Errorf("get migrate database driver: %w", err)
}
m, err = migrate.NewWithInstance(sourceName, sourceInstance, dbName, dbDriver)
if err == nil {
return m, nil
}
if !isDialError(err) {
return nil, fmt.Errorf("error while connecting to DB: %w", err)
}
if a.More() {
logging.Default().WithError(err).Info("Could not connect to DB: Trying again")
}
}
return nil, fmt.Errorf("retries exhausted, could not connect to DB: %w", err)
}
func closeMigrate(m *migrate.Migrate) {
srcErr, dbErr := m.Close()
if srcErr != nil {
logging.Default().WithError(srcErr).Error("failed to close source driver")
}
if dbErr != nil {
logging.Default().WithError(dbErr).Error("failed to close database connection")
}
}
func MigrateUp(p params.Database) error {
m, err := getMigrate(p)
if err != nil {
return err
}
defer closeMigrate(m)
err = m.Up()
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
return err
}
return nil
}
func MigrateDown(params params.Database) error {
m, err := getMigrate(params)
if err != nil {
return err
}
defer closeMigrate(m)
err = m.Down()
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
return err
}
return nil
}
func MigrateTo(ctx context.Context, p params.Database, version uint, force bool) error {
// make sure we have schema by calling connect
mdb, err := ConnectDB(ctx, p)
if err != nil {
return err
}
defer mdb.Close()
m, err := getMigrate(p)
if err != nil {
return err
}
defer closeMigrate(m)
if force {
err = m.Force(int(version))
} else {
err = m.Migrate(version)
}
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
return err
}
return nil
}
func MigrateVersion(ctx context.Context, dbPool Database, params params.Database) (uint, bool, error) {
// validate that default migrations table exists with information - a workaround
// so we will not create the migration table as the package will ensure the table exists
var rows int
err := dbPool.Get(ctx, &rows, `SELECT COUNT(*) FROM `+postgres.DefaultMigrationsTable)
if err != nil || rows == 0 {
return 0, false, migrate.ErrNilVersion
}
// get version from migrate
m, err := getMigrate(params)
if err != nil {
return 0, false, err
}
defer closeMigrate(m)
version, dirty, err := m.Version()
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
return 0, false, err
}
return version, dirty, err
}