修复IN/NOT IN 构建的BUG

This commit is contained in:
白茶清欢 2024-08-09 22:13:34 +08:00
parent 7126765fd5
commit 0b0e6a8da5

View File

@ -425,9 +425,9 @@ func optionToSql(o *Option) (sqlBuildResult string, bindValue []any) {
} }
if reflect.TypeOf(fieldValue).Kind() == reflect.Slice { if reflect.TypeOf(fieldValue).Kind() == reflect.Slice {
// 传入数组, in语句 // 传入数组, in语句
sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` in (?)") placeholder, dataList := parseInSql(fieldValue)
byteData, _ := json.Marshal(fieldValue) sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` IN ("+placeholder+")")
bindValue = append(bindValue, strings.TrimRight(strings.TrimLeft(string(byteData), "["), "]")) bindValue = append(bindValue, dataList...)
} else { } else {
sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` = ?") sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` = ?")
bindValue = append(bindValue, fieldValue) bindValue = append(bindValue, fieldValue)
@ -442,16 +442,16 @@ func optionToSql(o *Option) (sqlBuildResult string, bindValue []any) {
// in 语句 // in 语句
// 传入数组, in语句 // 传入数组, in语句
for fieldName, fieldValue := range o.In { for fieldName, fieldValue := range o.In {
sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` in (?)") placeholder, dataList := parseInSql(fieldValue)
byteData, _ := json.Marshal(fieldValue) sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` IN ("+placeholder+")")
bindValue = append(bindValue, strings.TrimRight(strings.TrimLeft(string(byteData), "["), "]")) bindValue = append(bindValue, dataList...)
} }
// not in 语句 // not in 语句
for fieldName, fieldValue := range o.NotIn { for fieldName, fieldValue := range o.NotIn {
sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` NOT IN (?)") placeholder, dataList := parseInSql(fieldValue)
byteData, _ := json.Marshal(fieldValue) sqlBuildResultBlockList = append(sqlBuildResultBlockList, "`"+fieldName+"` NOT IN ("+placeholder+")")
bindValue = append(bindValue, strings.TrimRight(strings.TrimLeft(string(byteData), "["), "]")) bindValue = append(bindValue, dataList...)
} }
// like 语句 // like 语句
@ -489,3 +489,22 @@ func optionToSql(o *Option) (sqlBuildResult string, bindValue []any) {
} }
return return
} }
// parseInSql 解析in语句需要绑定占位符以及数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 22:07 2024/8/9
func parseInSql(fieldValue any) (string, []any) {
byteData, _ := json.Marshal(fieldValue)
var dataList []any
decoder := json.NewDecoder(strings.NewReader(string(byteData)))
decoder.UseNumber()
_ = decoder.Decode(&dataList)
// 生成占位符
placeholderList := make([]string, 0)
for i := 0; i < len(dataList); i++ {
placeholderList = append(placeholderList, "?")
}
return strings.Join(placeholderList, ","), dataList
}