Skip to content

Commit

Permalink
contrib/gorm.io/gorm.v1: do not panic on open
Browse files Browse the repository at this point in the history
If passing a nil `*gorm.Config` to `Open`, we should not panic, but instead
pass nothing on to `gorm`.

Fixes #2559
  • Loading branch information
bendiknesbo committed Feb 14, 2024
1 parent dbe790f commit 4defff6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
8 changes: 7 additions & 1 deletion contrib/gorm.io/gorm.v1/gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,13 @@ const (
// Open opens a new (traced) database connection. The used driver must be formerly registered
// using (gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql).Register.
func Open(dialector gorm.Dialector, cfg *gorm.Config, opts ...Option) (*gorm.DB, error) {
db, err := gorm.Open(dialector, cfg)
var db *gorm.DB
var err error
if cfg != nil {
db, err = gorm.Open(dialector, cfg)
} else {
db, err = gorm.Open(dialector)
}
if err != nil {
return db, err
}
Expand Down
13 changes: 13 additions & 0 deletions contrib/gorm.io/gorm.v1/gorm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,19 @@ func TestMain(m *testing.M) {
os.Exit(testResult)
}

func TestOpenDoesNotPanic(t *testing.T) {
defer func() {
if r := recover(); r != nil {
assert.Fail(t, "Opening connection panicked", r)
}
}()
// None of the following calls should end up in a panic.
_, _ = gorm.Open(nil, &gorm.Config{})
_, _ = gorm.Open(nil, nil)
_, _ = Open(nil, &gorm.Config{})
_, _ = Open(nil, nil)
}

func TestMySQL(t *testing.T) {
sqltrace.Register("mysql", &mysql.MySQLDriver{}, sqltrace.WithServiceName("mysql-test"))
sqlDb, err := sqltrace.Open("mysql", mysqlConnString)
Expand Down

0 comments on commit 4defff6

Please sign in to comment.