Support named argument for struct

This commit is contained in:
Jinzhu 2020-09-17 21:52:41 +08:00
parent a932175ccf
commit d002c70cf6
3 changed files with 24 additions and 2 deletions

View File

@ -3,6 +3,7 @@ package clause
import ( import (
"database/sql" "database/sql"
"database/sql/driver" "database/sql/driver"
"go/ast"
"reflect" "reflect"
) )
@ -89,6 +90,17 @@ func (expr NamedExpr) Build(builder Builder) {
for k, v := range value { for k, v := range value {
namedMap[k] = v namedMap[k] = v
} }
default:
reflectValue := reflect.Indirect(reflect.ValueOf(value))
switch reflectValue.Kind() {
case reflect.Struct:
modelType := reflectValue.Type()
for i := 0; i < modelType.NumField(); i++ {
if fieldStruct := modelType.Field(i); ast.IsExported(fieldStruct.Name) {
namedMap[fieldStruct.Name] = reflectValue.Field(i).Interface()
}
}
}
} }
} }

View File

@ -37,6 +37,11 @@ func TestExpr(t *testing.T) {
} }
func TestNamedExpr(t *testing.T) { func TestNamedExpr(t *testing.T) {
type NamedArgument struct {
Name1 string
Name2 string
}
results := []struct { results := []struct {
SQL string SQL string
Result string Result string
@ -66,6 +71,11 @@ func TestNamedExpr(t *testing.T) {
Vars: []interface{}{sql.Named("name1", "jinzhu"), sql.Named("name2", "jinzhu2")}, Vars: []interface{}{sql.Named("name1", "jinzhu"), sql.Named("name2", "jinzhu2")},
Result: "@@test AND name1 = ? AND name2 = ? AND name3 = ? ?", Result: "@@test AND name1 = ? AND name2 = ? AND name3 = ? ?",
ExpectedVars: []interface{}{"jinzhu", "jinzhu2", "jinzhu", nil}, ExpectedVars: []interface{}{"jinzhu", "jinzhu2", "jinzhu", nil},
}, {
SQL: "@@test AND name1 = @Name1 AND name2 = @Name2 AND name3 = @Name1 @Notexist",
Vars: []interface{}{NamedArgument{Name1: "jinzhu", Name2: "jinzhu2"}},
Result: "@@test AND name1 = ? AND name2 = ? AND name3 = ? ?",
ExpectedVars: []interface{}{"jinzhu", "jinzhu2", "jinzhu", nil},
}} }}
for idx, result := range results { for idx, result := range results {

View File

@ -8,9 +8,9 @@ require (
github.com/lib/pq v1.6.0 github.com/lib/pq v1.6.0
gorm.io/driver/mysql v1.0.1 gorm.io/driver/mysql v1.0.1
gorm.io/driver/postgres v1.0.0 gorm.io/driver/postgres v1.0.0
gorm.io/driver/sqlite v1.1.2 gorm.io/driver/sqlite v1.1.3
gorm.io/driver/sqlserver v1.0.4 gorm.io/driver/sqlserver v1.0.4
gorm.io/gorm v1.20.0 gorm.io/gorm v1.20.1
) )
replace gorm.io/gorm => ../ replace gorm.io/gorm => ../