Files
ginframework/database/query/condition.go
T
2026-11-28 03:10:18 -08:00

151 lines
3.3 KiB
Go

package query
import (
"reflect"
"sort"
"gorm.io/gorm/clause"
)
// optionExpressions 构造 OR 分支表达式,字段值保持参数绑定,避免重建占位符时丢失类型。
// 入参:option 为所属 OR 分支的可信字段条件。
// 返回:可由 GORM 正确加括号的独立条件表达式。
func optionExpressions(option *Option) []clause.Expression {
var (
result []clause.Expression
)
for _, key := range sortedKeys(option.Where) {
result = append(result, clause.Eq{
Column: clause.Column{
Name: key,
},
Value: option.Where[key],
})
}
for _, key := range sortedKeys(option.In) {
result = append(result, clause.IN{
Column: clause.Column{
Name: key,
},
Values: sliceValues(option.In[key]),
})
}
for _, key := range sortedKeys(option.NotIn) {
result = append(result, clause.Not(clause.IN{
Column: clause.Column{
Name: key,
},
Values: sliceValues(option.NotIn[key]),
}))
}
for _, key := range sortedKeys(option.Like) {
result = append(result, clause.Like{
Column: clause.Column{
Name: key,
},
Value: "%" + option.Like[key] + "%",
})
}
for _, key := range sortedKeys(option.NotLike) {
result = append(result, clause.Not(clause.Like{
Column: clause.Column{
Name: key,
},
Value: "%" + option.NotLike[key] + "%",
}))
}
for _, key := range sortedKeys(option.NotEqual) {
result = append(result, clause.Neq{
Column: clause.Column{
Name: key,
},
Value: option.NotEqual[key],
})
}
for _, key := range sortedKeys(option.Start) {
result = append(result, clause.Gte{
Column: clause.Column{
Name: key,
},
Value: option.Start[key],
})
}
for _, key := range sortedKeys(option.End) {
result = append(result, clause.Lt{
Column: clause.Column{
Name: key,
},
Value: option.End[key],
})
}
for _, key := range sortedKeys(option.Between) {
var (
bounds = option.Between[key]
)
result = append(result, clause.And(clause.Gte{
Column: clause.Column{
Name: key,
},
Value: bounds[0],
}, clause.Lte{
Column: clause.Column{
Name: key,
},
Value: bounds[1],
}))
}
for _, key := range sortedKeys(option.NotBetween) {
var (
bounds = option.NotBetween[key]
)
result = append(result, clause.Or(clause.Lt{
Column: clause.Column{
Name: key,
},
Value: bounds[0],
}, clause.Gt{
Column: clause.Column{
Name: key,
},
Value: bounds[1],
}))
}
return result
}
// sortedKeys 稳定生成 SQL 表达式顺序,不影响条件语义。
// 入参:values 为可信字段与条件值的映射。
// 返回:排序后的字段键列表。
func sortedKeys[T any](values map[string]T) []string {
var (
keys = make([]string, 0, len(values))
)
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
// sliceValues 保留 IN 参数的真实类型,不通过 JSON 转换整型和字节值。
// 入参:value 为已由查询 option 接受的切片值。
// 返回:供 GORM 绑定的参数列表。
func sliceValues(value any) []any {
var (
v = reflect.ValueOf(value)
result []any
)
if !v.IsValid() {
return nil
}
if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
return []any{value}
}
result = make([]any, v.Len())
for i := range v.Len() {
result[i] = v.Index(i).Interface()
}
return result
}