Merge branch 'master' into patch-1

This commit is contained in:
Jinzhu 2018-11-03 22:15:33 +08:00 committed by GitHub
commit d7e23b1f6c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 30 additions and 3 deletions

View File

@ -368,6 +368,7 @@ func (association *Association) saveAssociations(values ...interface{}) *Associa
return association
}
// setErr set error when the error is not nil. And return Association.
func (association *Association) setErr(err error) *Association {
if err != nil {
association.Error = err

View File

@ -2,6 +2,7 @@ package gorm
import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"reflect"
@ -44,7 +45,14 @@ func (field *Field) Set(value interface{}) (err error) {
if reflectValue.Type().ConvertibleTo(fieldValue.Type()) {
fieldValue.Set(reflectValue.Convert(fieldValue.Type()))
} else if scanner, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {
err = scanner.Scan(reflectValue.Interface())
v := reflectValue.Interface()
if valuer, ok := v.(driver.Valuer); ok {
if v, err = valuer.Value(); err == nil {
err = scanner.Scan(v)
}
} else {
err = scanner.Scan(v)
}
} else {
err = fmt.Errorf("could not convert argument of field %s from %s to %s", field.Name, reflectValue.Type(), fieldValue.Type())
}

View File

@ -3,6 +3,7 @@ package gorm_test
import (
"testing"
"github.com/gofrs/uuid"
"github.com/jinzhu/gorm"
)
@ -47,3 +48,20 @@ func TestCalculateField(t *testing.T) {
t.Errorf("should find embedded field's tag settings")
}
}
func TestFieldSet(t *testing.T) {
type TestFieldSetNullUUID struct {
NullUUID uuid.NullUUID
}
scope := DB.NewScope(&TestFieldSetNullUUID{})
field := scope.Fields()[0]
err := field.Set(uuid.FromStringOrNil("3034d44a-da03-11e8-b366-4a00070b9f00"))
if err != nil {
t.Fatal(err)
}
if id, ok := field.Field.Addr().Interface().(*uuid.NullUUID); !ok {
t.Fatal()
} else if !id.Valid || id.UUID.String() != "3034d44a-da03-11e8-b366-4a00070b9f00" {
t.Fatal(id)
}
}

View File

@ -68,7 +68,7 @@ func (scope *Scope) Dialect() Dialect {
// Quote used to quote string to escape them for database
func (scope *Scope) Quote(str string) string {
if strings.Index(str, ".") != -1 {
if strings.Contains(str, ".") {
newStrs := []string{}
for _, str := range strings.Split(str, ".") {
newStrs = append(newStrs, scope.Dialect().Quote(str))
@ -330,7 +330,7 @@ func (scope *Scope) TableName() string {
// QuotedTableName return quoted table name
func (scope *Scope) QuotedTableName() (name string) {
if scope.Search != nil && len(scope.Search.tableName) > 0 {
if strings.Index(scope.Search.tableName, " ") != -1 {
if strings.Contains(scope.Search.tableName, " ") {
return scope.Search.tableName
}
return scope.Quote(scope.Search.tableName)