Skip to content

Commit

Permalink
BCF-3322: automatically cleanup heavyweight test databases (#13843)
Browse files Browse the repository at this point in the history
  • Loading branch information
krehermann authored Jul 15, 2024
1 parent 9227095 commit 3155711
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/silver-peas-happen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"chainlink": minor
---

#internal cleanup heavyweight test databases automatically
4 changes: 2 additions & 2 deletions core/internal/cltest/heavyweight/orm.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"testing"

"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/jmoiron/sqlx"
Expand Down Expand Up @@ -68,7 +67,8 @@ func (c Kind) PrepareDB(t testing.TB, overrideFn func(c *chainlink.Config, s *ch
db, err := pg.NewConnection(migrationTestDBURL, dialects.Postgres, gcfg.Database())
require.NoError(t, err)
t.Cleanup(func() {
assert.NoError(t, db.Close())
require.NoError(t, db.Close()) // must close before dropping
require.NoError(t, testdb.Drop(*testutils.MustParseURL(t, migrationTestDBURL)))
os.RemoveAll(gcfg.RootDir())
})

Expand Down
25 changes: 25 additions & 0 deletions internal/testdb/testdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/url"
"strings"

"github.com/smartcontractkit/chainlink/v2/core/store/dialects"
)
Expand Down Expand Up @@ -54,3 +55,27 @@ func CreateOrReplace(parsed url.URL, suffix string, withTemplate bool) (string,
parsed.Path = fmt.Sprintf("/%s", dbname)
return parsed.String(), nil
}

// Drop drops the database at the given URL.
func Drop(dbURL url.URL) error {
if dbURL.Path == "" {
return errors.New("path missing from database URL")
}
dbname := strings.TrimPrefix(dbURL.Path, "/")

// Cannot drop test database if we are connected to it, so we must connect
// to a different one. 'postgres' should be present on all postgres installations
dbURL.Path = "/postgres"
db, err := sql.Open(string(dialects.Postgres), dbURL.String())
if err != nil {
return fmt.Errorf("in order to drop the test database, we need to connect to a separate database"+
" called 'postgres'. But we are unable to open 'postgres' database: %+v\n", err)
}
defer db.Close()

_, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", dbname))
if err != nil {
return fmt.Errorf("unable to drop postgres migrations test database: %v", err)
}
return nil
}

0 comments on commit 3155711

Please sign in to comment.