refact: Add db.DB wrapper and refact all test fixtures to use it. (#1535)

* refact: Changes required for gorm v2

* refact: Add db.DB wrapper and refact all test fixtures to use it

Stop leaking the gorm abstraction within our unit tests.

* refact: Migrate direct calls to pq to pgx driver

The refactor will remove the remaining direct dependencies on
the pq driver which has been deprecated in favor of the pgx
driver.

It includes the addition of common.SqlOpen which is a wrapper around
sql.Open, which is needed to deal with the driver name changing from
"postgres" to "pgx" but in our code base the dialect and driver are
synonyms.
This commit is contained in:
Jim authored and GitHub committed 2021-09-30 09:17:27 -04:00
1 parent 136ac00b49
commit 8d6dee09a9
77 files changed
+441 -321

No files matched your search

+1 -1
View File
@@ -94,7 +94,7 @@ func (b *Server) CreateDevDatabase(ctx context.Context, opt ...Option) error {
b.Info["dev database container"] = strings.TrimPrefix(container, "/")
}
if err := b.ConnectToDatabase(dialect); err != nil {
if err := b.ConnectToDatabase(ctx, dialect); err != nil {
if c != nil {
err = multierror.Append(err, c())
}
@@ -4,11 +4,12 @@
package docker
import (
"database/sql"
"fmt"
"os"
"strings"
"github.com/hashicorp/boundary/internal/db/common"
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/ory/dockertest/v3"
)
@@ -37,7 +38,7 @@ func startDbInDockerSupported(dialect string, opt ...Option) (cleanup func() err
}
switch dialect {
case "postgres":
case "postgres", "pgx":
switch {
case os.Getenv("BOUNDARY_TESTING_PG_URL") != "":
url = os.Getenv("BOUNDARY_TESTING_PG_URL")
@@ -68,7 +69,7 @@ func startDbInDockerSupported(dialect string, opt ...Option) (cleanup func() err
}
if err := pool.Retry(func() error {
db, err := sql.Open(dialect, url)
db, err := common.SqlOpen(dialect, url)
if err != nil {
return fmt.Errorf("error opening %s dev container: %w", dialect, err)
}
+11 -31
View File
@@ -39,8 +39,6 @@ import (
"github.com/hashicorp/go-secure-stdlib/strutil"
"github.com/mitchellh/cli"
"google.golang.org/grpc/grpclog"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
const (
@@ -120,7 +118,7 @@ type Server struct {
DatabaseMaxOpenConnections int
DevDatabaseCleanupFunc func() error
Database *gorm.DB
Database *db.DB
// StatusGracePeriodDuration represents the period of time (as a
// duration) that the controller will wait before marking
@@ -548,38 +546,22 @@ func (b *Server) RunShutdownFuncs() error {
return mErr.ErrorOrNil()
}
func (b *Server) ConnectToDatabase(dialect string) error {
func (b *Server) ConnectToDatabase(ctx context.Context, dialect string) error {
dbType, err := db.StringToDbType(dialect)
if err != nil {
return fmt.Errorf("unable to create db object with dialect %s: %w", dialect, err)
}
dbase, err := db.Open(dbType, b.DatabaseUrl)
opts := []db.Option{
db.WithMaxOpenConnections(b.DatabaseMaxOpenConnections),
}
if os.Getenv("BOUNDARY_DISABLE_GORM_FORMATTER") == "" {
opts = append(opts, db.WithGormFormatter(b.Logger))
}
dbase, err := db.Open(dbType, b.DatabaseUrl, opts...)
if err != nil {
return fmt.Errorf("unable to create db object with dialect %s: %w", dialect, err)
}
if b.DatabaseMaxOpenConnections == 1 {
return fmt.Errorf("unable to create db object with dialect %s: %s", dialect, "max_open_connections must be unlimited by setting 0 or at least 2")
} else {
underlyingDB, err := dbase.DB()
if err != nil {
return fmt.Errorf("unable retreive db: %w", err)
}
underlyingDB.SetMaxOpenConns(b.DatabaseMaxOpenConnections)
}
b.Database = dbase
if os.Getenv("BOUNDARY_DISABLE_GORM_FORMATTER") == "" {
newLogger := logger.New(
db.GetGormLogger(b.Logger),
logger.Config{
LogLevel: logger.Error, // Log level
Colorful: false, // Disable color
},
)
dbase = dbase.Session(&gorm.Session{Logger: newLogger})
}
b.Database = dbase
return nil
}
@@ -618,13 +600,11 @@ func (b *Server) CreateGlobalKmsKeys(ctx context.Context) error {
return nil
}
func (b *Server) DestroyDevDatabase() error {
func (b *Server) DestroyDevDatabase(ctx context.Context) error {
if b.Database != nil {
underlyingDB, err := b.Database.DB()
if err != nil {
if err := b.Database.Close(ctx); err != nil {
return err
}
underlyingDB.Close()
}
if b.DevDatabaseCleanupFunc != nil {
return b.DevDatabaseCleanupFunc()
+2 -2
View File
@@ -2,10 +2,10 @@ package database
import (
"context"
"database/sql"
"fmt"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/db/common"
"github.com/hashicorp/boundary/internal/db/schema"
"github.com/hashicorp/boundary/internal/errors"
"github.com/mitchellh/cli"
@@ -20,7 +20,7 @@ func migrateDatabase(ctx context.Context, ui cli.Ui, dialect, u string, initiali
noop := func() {}
// This database is used to keep an exclusive lock on the database for the
// remainder of the command
dBase, err := sql.Open(dialect, u)
dBase, err := common.SqlOpen(dialect, u)
if err != nil {
ui.Error(fmt.Errorf("Error establishing db connection: %w", err).Error())
return noop, 2
+10 -10
View File
@@ -2,10 +2,10 @@ package database
import (
"context"
"database/sql"
"testing"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/db/common"
"github.com/hashicorp/boundary/internal/db/schema"
"github.com/hashicorp/boundary/testing/dbtest"
"github.com/mitchellh/cli"
@@ -49,7 +49,7 @@ func TestMigrateDatabase(t *testing.T) {
require.NoError(t, c())
})
dBase, err := sql.Open(dialect, u)
dBase, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
earlyMigrationVersion := 2000
@@ -75,7 +75,7 @@ func TestMigrateDatabase(t *testing.T) {
require.NoError(t, c())
})
dBase, err := sql.Open(dialect, u)
dBase, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
earlyMigrationVersion := 2000
@@ -100,7 +100,7 @@ func TestMigrateDatabase(t *testing.T) {
t.Cleanup(func() {
require.NoError(t, c())
})
dBase, err := sql.Open(dialect, u)
dBase, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
createStmt := `create table if not exists schema_migrations (version bigint primary key, dirty boolean not null)`
@@ -120,7 +120,7 @@ func TestMigrateDatabase(t *testing.T) {
t.Cleanup(func() {
require.NoError(t, c())
})
dBase, err := sql.Open(dialect, u)
dBase, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
createStmt := `create table if not exists schema_migrations (version bigint primary key, dirty boolean not null)`
@@ -154,7 +154,7 @@ func TestMigrateDatabase(t *testing.T) {
t.Cleanup(func() {
require.NoError(t, c())
})
dBase, err := sql.Open(dialect, u)
dBase, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
man, err := schema.NewManager(ctx, dialect, dBase)
@@ -177,7 +177,7 @@ func TestMigrateDatabase(t *testing.T) {
t.Cleanup(func() {
require.NoError(t, c())
})
dBase, err := sql.Open(dialect, u)
dBase, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
man, err := schema.NewManager(ctx, dialect, dBase)
@@ -217,7 +217,7 @@ func TestVerifyOplogIsEmpty(t *testing.T) {
})
_ = c
dBase, err := sql.Open(dialect, u)
dBase, err := common.SqlOpen(dialect, u)
require.NoError(t, err)
man, err := schema.NewManager(ctx, dialect, dBase)
@@ -228,7 +228,7 @@ func TestVerifyOplogIsEmpty(t *testing.T) {
cmd.srv = base.NewServer(&base.Command{UI: cmd.UI})
cmd.srv.DatabaseUrl = u
require.NoError(t, cmd.srv.ConnectToDatabase(dialect))
require.NoError(t, cmd.srv.ConnectToDatabase(ctx, dialect))
assert.NoError(t, cmd.verifyOplogIsEmpty())
assert.NoError(t, cmd.verifyOplogIsEmpty(ctx))
}
+6 -4
View File
@@ -1,6 +1,7 @@
package database
import (
"context"
"fmt"
"github.com/hashicorp/boundary/internal/cmd/base"
@@ -164,6 +165,7 @@ func (c *InitCommand) AutocompleteFlags() complete.Flags {
}
func (c *InitCommand) Run(args []string) (retCode int) {
ctx := context.Background()
if result := c.ParseFlagsAndConfig(args); result > 0 {
return result
}
@@ -277,11 +279,11 @@ func (c *InitCommand) Run(args []string) (retCode int) {
return base.CommandUserError
}
// Everything after is done with normal database URL and is affecting actual data
if err := c.srv.ConnectToDatabase(dialect); err != nil {
if err := c.srv.ConnectToDatabase(ctx, dialect); err != nil {
c.UI.Error(fmt.Errorf("Error connecting to database after migrations: %w", err).Error())
return base.CommandCliError
}
if err := c.verifyOplogIsEmpty(); err != nil {
if err := c.verifyOplogIsEmpty(ctx); err != nil {
c.UI.Error(fmt.Sprintf("The database appears to have already been initialized: %v", err))
return base.CommandCliError
}
@@ -491,9 +493,9 @@ func (c *InitCommand) ParseFlagsAndConfig(args []string) int {
return base.CommandSuccess
}
func (c *InitCommand) verifyOplogIsEmpty() error {
func (c *InitCommand) verifyOplogIsEmpty(ctx context.Context) error {
const op = "database.(InitCommand).verifyOplogIsEmpty"
underlyingDB, err := c.srv.Database.DB()
underlyingDB, err := c.srv.Database.SqlDB(ctx)
if err != nil {
return errors.NewDeprecated(errors.Internal, op, "unable to retreive db", errors.WithWrap(err))
}
+1 -1
View File
@@ -556,7 +556,7 @@ func (c *Command) Run(args []string) int {
}
if !c.flagDisableDatabaseDestruction {
c.ShutdownFuncs = append(c.ShutdownFuncs, c.DestroyDevDatabase)
c.ShutdownFuncs = append(c.ShutdownFuncs, func() error { return c.DestroyDevDatabase(ctx) })
}
default:
c.DatabaseUrl, err = parseutil.ParsePath(c.flagDatabaseUrl)
+2 -2
View File
@@ -389,12 +389,12 @@ func (c *Command) Run(args []string) int {
}
c.DatabaseMaxOpenConnections = c.Config.Controller.Database.MaxOpenConnections
if err := c.ConnectToDatabase("postgres"); err != nil {
if err := c.ConnectToDatabase(ctx, "postgres"); err != nil {
c.UI.Error(fmt.Errorf("Error connecting to database: %w", err).Error())
return base.CommandCliError
}
underlyingDB, err := c.Database.DB()
underlyingDB, err := c.Database.SqlDB(ctx)
if err != nil {
c.UI.Error(fmt.Errorf("Can't get db: %w.", err).Error())
return base.CommandCliError