Support named argument for struct
This commit is contained in:
		
							parent
							
								
									a932175ccf
								
							
						
					
					
						commit
						d002c70cf6
					
				| @ -3,6 +3,7 @@ package clause | ||||
| import ( | ||||
| 	"database/sql" | ||||
| 	"database/sql/driver" | ||||
| 	"go/ast" | ||||
| 	"reflect" | ||||
| ) | ||||
| 
 | ||||
| @ -89,6 +90,17 @@ func (expr NamedExpr) Build(builder Builder) { | ||||
| 			for k, v := range value { | ||||
| 				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() | ||||
| 					} | ||||
| 				} | ||||
| 			} | ||||
| 		} | ||||
| 	} | ||||
| 
 | ||||
|  | ||||
| @ -37,6 +37,11 @@ func TestExpr(t *testing.T) { | ||||
| } | ||||
| 
 | ||||
| func TestNamedExpr(t *testing.T) { | ||||
| 	type NamedArgument struct { | ||||
| 		Name1 string | ||||
| 		Name2 string | ||||
| 	} | ||||
| 
 | ||||
| 	results := []struct { | ||||
| 		SQL          string | ||||
| 		Result       string | ||||
| @ -66,6 +71,11 @@ func TestNamedExpr(t *testing.T) { | ||||
| 		Vars:         []interface{}{sql.Named("name1", "jinzhu"), sql.Named("name2", "jinzhu2")}, | ||||
| 		Result:       "@@test AND name1 = ? AND name2 = ? AND name3 = ? ?", | ||||
| 		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 { | ||||
|  | ||||
| @ -8,9 +8,9 @@ require ( | ||||
| 	github.com/lib/pq v1.6.0 | ||||
| 	gorm.io/driver/mysql v1.0.1 | ||||
| 	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/gorm v1.20.0 | ||||
| 	gorm.io/gorm v1.20.1 | ||||
| ) | ||||
| 
 | ||||
| replace gorm.io/gorm => ../ | ||||
|  | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user
	 Jinzhu
						Jinzhu