add simple input validation on gorm.Open function (#1855)

Simply check if the passed-in database source meets the expected types
and, if not, early return with error.
This commit is contained in:
Daniel McDonald 2018-05-02 07:37:51 -07:00 committed by Jinzhu
parent 6842b49a1a
commit 35efe68ba7
2 changed files with 19 additions and 0 deletions

View File

@ -61,6 +61,8 @@ func Open(dialect string, args ...interface{}) (db *DB, err error) {
dbSQL, err = sql.Open(driver, source)
case SQLCommon:
dbSQL = value
default:
return nil, fmt.Errorf("invalid database source: %v is not a valid type", value)
}
db = &DB{

View File

@ -8,6 +8,7 @@ import (
"path/filepath"
"reflect"
"strconv"
"strings"
"testing"
"time"
@ -79,6 +80,22 @@ func OpenTestConnection() (db *gorm.DB, err error) {
return
}
func TestOpen_ReturnsError_WithBadArgs(t *testing.T) {
stringRef := "foo"
testCases := []interface{}{42, time.Now(), &stringRef}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%v", tc), func(t *testing.T) {
_, err := gorm.Open("postgresql", tc)
if err == nil {
t.Error("Should got error with invalid database source")
}
if !strings.HasPrefix(err.Error(), "invalid database source:") {
t.Errorf("Should got error starting with \"invalid database source:\", but got %q", err.Error())
}
})
}
}
func TestStringPrimaryKey(t *testing.T) {
type UUIDStruct struct {
ID string `gorm:"primary_key"`