2019-01-24 20:15:10 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
2018-10-25 18:11:28 +01:00
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
//go:generate go-bindata -o data.go -pkg schema -ignore ".*go" .
|
|
|
|
|
|
|
|
package schema
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
|
2019-11-02 20:09:07 +00:00
|
|
|
"github.com/golang-migrate/migrate/v4"
|
|
|
|
"github.com/golang-migrate/migrate/v4/database/postgres"
|
|
|
|
bindata "github.com/golang-migrate/migrate/v4/source/go_bindata"
|
2019-05-14 16:13:18 +01:00
|
|
|
"github.com/zeebo/errs"
|
|
|
|
|
|
|
|
"storj.io/storj/internal/dbutil/pgutil"
|
2018-10-25 18:11:28 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// PrepareDB applies schema migrations as necessary to the given database to
|
|
|
|
// get it up to date.
|
2019-05-14 16:13:18 +01:00
|
|
|
func PrepareDB(db *sql.DB, dbURL string) error {
|
2019-05-29 14:14:25 +01:00
|
|
|
srcDriver, err := bindata.WithInstance(bindata.Resource(AssetNames(), Asset))
|
2018-10-25 18:11:28 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-05-14 16:13:18 +01:00
|
|
|
|
|
|
|
schema, err := pgutil.ParseSchemaFromConnstr(dbURL)
|
|
|
|
if err != nil {
|
|
|
|
return errs.New("error parsing schema: %+v", err)
|
|
|
|
}
|
|
|
|
if schema != "" {
|
|
|
|
err := pgutil.CreateSchema(db, schema)
|
|
|
|
if err != nil {
|
|
|
|
return errs.New("error creating schema: %+v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-25 18:11:28 +01:00
|
|
|
dbDriver, err := postgres.WithInstance(db, &postgres.Config{})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
m, err := migrate.NewWithInstance("go-bindata migrations", srcDriver, "postgreskv db", dbDriver)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = m.Up()
|
|
|
|
if err == migrate.ErrNoChange {
|
|
|
|
err = nil
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|