storj/private/migrate/db.go
JT Olio 8e242cd012 dbutil: statically require all databases accesses to use contexts
this will allow for some nice runtime analysis down the road.
also, this allows for wrapping database handles in a way that
can interact with these contexts

requires https://review.dev.storj.io/c/storj/dbx/+/514

Change-Id: Ib087b7cd73296dd2c1e0331314da34d861f61d2b
2020-01-14 18:20:47 -05:00

50 lines
1.2 KiB
Go

// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package migrate
import (
"context"
"database/sql"
"database/sql/driver"
"storj.io/storj/private/dbutil/dbwrap"
"storj.io/storj/private/dbutil/txutil"
)
// 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 {
BeginTx(ctx context.Context, txOptions *sql.TxOptions) (dbwrap.Tx, error)
DriverContext(context.Context) driver.Driver
}
// 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 {
if dbx, ok := db.(interface {
Rebind(string) string
}); ok {
return dbx.Rebind(s)
}
return s
}
// WithTx runs the given callback in the context of a transaction.
func WithTx(ctx context.Context, db DB, fn func(ctx context.Context, tx dbwrap.Tx) error) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
return txutil.ExecuteInTx(ctx, db.DriverContext(ctx), tx, func() error {
return fn(ctx, tx)
})
}