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" .
|
2019-11-22 18:17:02 +00:00
|
|
|
//go:generate bash -c "sed -i'' '1i //lint:file-ignore * generated file\n' data.go"
|
2018-10-25 18:11:28 +01:00
|
|
|
|
|
|
|
package schema
|
|
|
|
|
|
|
|
import (
|
2020-01-13 13:18:48 +00:00
|
|
|
"context"
|
2018-10-25 18:11:28 +01:00
|
|
|
"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"
|
|
|
|
|
2019-11-14 19:46:15 +00:00
|
|
|
"storj.io/storj/private/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.
|
2020-01-13 13:18:48 +00:00
|
|
|
func PrepareDB(ctx context.Context, 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 != "" {
|
2020-01-13 13:18:48 +00:00
|
|
|
err := pgutil.CreateSchema(ctx, db, schema)
|
2019-05-14 16:13:18 +01:00
|
|
|
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
|
|
|
|
}
|