added support sql.NamedArg

This commit is contained in:
Nikita Koryabkin 2019-11-28 13:54:55 +03:00
parent 59408390c2
commit 922b2b665f
3 changed files with 26 additions and 2 deletions

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
documents documents
coverage.txt coverage.txt
_book _book
.idea

View File

@ -1,6 +1,7 @@
package gorm package gorm
import ( import (
"database/sql"
"fmt" "fmt"
"strings" "strings"
) )
@ -65,7 +66,8 @@ func createCallback(scope *Scope) {
scope.InstanceSet("gorm:blank_columns_with_default_value", blankColumnsWithDefaultValue) scope.InstanceSet("gorm:blank_columns_with_default_value", blankColumnsWithDefaultValue)
} else if !field.IsPrimaryKey || !field.IsBlank { } else if !field.IsPrimaryKey || !field.IsBlank {
columns = append(columns, scope.Quote(field.DBName)) columns = append(columns, scope.Quote(field.DBName))
placeholders = append(placeholders, scope.AddToVars(field.Field.Interface())) arg := sql.NamedArg{Name: field.StructField.DBName, Value: field.Field.Interface()}
placeholders = append(placeholders, scope.AddToVars(arg))
} }
} else if field.Relationship != nil && field.Relationship.Kind == "belongs_to" { } else if field.Relationship != nil && field.Relationship.Kind == "belongs_to" {
for _, foreignKey := range field.Relationship.ForeignDBNames { for _, foreignKey := range field.Relationship.ForeignDBNames {

View File

@ -269,7 +269,11 @@ func (scope *Scope) AddToVars(value interface{}) string {
return exp return exp
} }
if val, ok := value.(sql.NamedArg); ok {
scope.SQLVars = append(scope.SQLVars, val.Value)
} else {
scope.SQLVars = append(scope.SQLVars, value) scope.SQLVars = append(scope.SQLVars, value)
}
if skipBindVar { if skipBindVar {
return "?" return "?"
@ -580,6 +584,14 @@ func (scope *Scope) buildCondition(clause map[string]interface{}, include bool)
} }
} }
return strings.Join(sqls, " AND ") return strings.Join(sqls, " AND ")
case []sql.NamedArg:
var sqls []string
for _, val := range value {
if len(val.Name) != 0 {
sqls = append(sqls, fmt.Sprintf("(%v.%v %s %v)", quotedTableName, scope.Quote(val.Name), equalSQL, scope.AddToVars(val)))
}
}
return strings.Join(sqls, " AND ")
case interface{}: case interface{}:
var sqls []string var sqls []string
newScope := scope.New(value) newScope := scope.New(value)
@ -878,6 +890,14 @@ func convertInterfaceToMap(values interface{}, withIgnoredField bool, db *DB) ma
switch value := values.(type) { switch value := values.(type) {
case map[string]interface{}: case map[string]interface{}:
return value return value
case []sql.NamedArg:
for _, v := range value {
for key, value := range convertInterfaceToMap(v, withIgnoredField, db) {
attrs[key] = value
}
}
case sql.NamedArg:
attrs[value.Name] = value.Value
case []interface{}: case []interface{}:
for _, v := range value { for _, v := range value {
for key, value := range convertInterfaceToMap(v, withIgnoredField, db) { for key, value := range convertInterfaceToMap(v, withIgnoredField, db) {