2019-09-20 17:26:07 +01:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package migrate
|
|
|
|
|
|
|
|
import (
|
2019-12-19 09:14:56 +00:00
|
|
|
"context"
|
2019-09-20 17:26:07 +01:00
|
|
|
"database/sql"
|
2019-12-19 09:14:56 +00:00
|
|
|
"database/sql/driver"
|
|
|
|
|
|
|
|
"storj.io/storj/private/dbutil/txutil"
|
2020-01-17 18:22:44 +00:00
|
|
|
"storj.io/storj/private/tagsql"
|
2019-09-20 17:26:07 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// DB is the minimal implementation that is needed by migrations.
|
|
|
|
//
|
|
|
|
// DB can optionally have `Rebind(string) string` for translating `? queries for the specific database.
|
|
|
|
type DB interface {
|
2020-01-17 18:22:44 +00:00
|
|
|
BeginTx(ctx context.Context, txOptions *sql.TxOptions) (tagsql.Tx, error)
|
2020-01-15 07:25:26 +00:00
|
|
|
Driver() driver.Driver
|
2019-09-20 17:26:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// DBX contains additional methods for migrations.
|
|
|
|
type DBX interface {
|
|
|
|
DB
|
|
|
|
Schema() string
|
|
|
|
Rebind(string) string
|
|
|
|
}
|
|
|
|
|
|
|
|
// rebind uses Rebind method when the database has the func.
|
|
|
|
func rebind(db DB, s string) string {
|
2020-01-15 07:25:26 +00:00
|
|
|
if dbx, ok := db.(interface{ Rebind(string) string }); ok {
|
2019-09-20 17:26:07 +01:00
|
|
|
return dbx.Rebind(s)
|
|
|
|
}
|
|
|
|
return s
|
|
|
|
}
|
2019-12-19 09:14:56 +00:00
|
|
|
|
|
|
|
// WithTx runs the given callback in the context of a transaction.
|
2020-01-17 18:22:44 +00:00
|
|
|
func WithTx(ctx context.Context, db DB, fn func(ctx context.Context, tx tagsql.Tx) error) error {
|
2019-12-19 09:14:56 +00:00
|
|
|
tx, err := db.BeginTx(ctx, nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-01-15 07:25:26 +00:00
|
|
|
return txutil.ExecuteInTx(ctx, db.Driver(), tx, func() error {
|
2019-12-19 09:14:56 +00:00
|
|
|
return fn(ctx, tx)
|
|
|
|
})
|
|
|
|
}
|