sql-builder/db/add_sql.go

57 lines
1.7 KiB
Go
Raw Normal View History

2024-04-29 15:59:38 +08:00
package db
import (
"fmt"
"reflect"
"strings"
)
// 如果添加的条件是in条件,则格式为"id in (?)",args参数为slice类型并且每次调用该方法只能有一个in条件
func (s *SqlBuilder[T]) Conditions(cond string, args ...interface{}) {
if strings.HasPrefix(cond, " and") {
cond = strings.Join(strings.Split(cond, " and")[1:], " and ")
}
cond, args = dealInCondition(cond, args)
2024-05-07 17:19:55 +08:00
s.Opts.conditions = append(s.Opts.conditions, cond)
2024-04-29 15:59:38 +08:00
s.Opts.args = append(s.Opts.args, args...)
}
func (s *SqlBuilder[T]) Selects(selects ...string) {
2024-05-07 17:19:55 +08:00
s.Opts.selects = append(s.Opts.selects, selects...)
2024-04-29 15:59:38 +08:00
}
func (s *SqlBuilder[T]) Groups(groups ...string) {
2024-05-07 17:19:55 +08:00
s.Opts.groups = append(s.Opts.groups, groups...)
2024-04-29 15:59:38 +08:00
}
func (s *SqlBuilder[T]) Orders(orders ...string) {
2024-05-07 17:19:55 +08:00
s.Opts.orders = append(s.Opts.orders, orders...)
2024-04-29 15:59:38 +08:00
}
func (s *SqlBuilder[T]) Partitions(partitions ...string) {
2024-05-07 17:19:55 +08:00
s.Opts.partitions = append(s.Opts.partitions, partitions...)
2024-04-29 15:59:38 +08:00
}
func dealInCondition(cond string, args []interface{}) (string, []interface{}) {
if ok := strings.Contains(cond, "(?)"); !ok {
return cond, args
}
var newArgs []interface{}
for i := 0; i < len(args); i++ {
//判断args参数是否为slice
if reflect.TypeOf(args[i]).Kind() == reflect.Slice {
var str []string
for j := 0; j < reflect.ValueOf(args[i]).Len(); j++ {
//如果是slice则将cond里的?替代为args的长度个?
str = append(str, "?")
//将args[i]里的元素添加到new_args里
newArgs = append(newArgs, reflect.ValueOf(args[i]).Index(j).Interface())
}
cond = strings.Replace(cond, "(?)", fmt.Sprintf("(%s)", strings.Join(str, ",")), -1)
} else {
newArgs = append(newArgs, args[i])
}
}
return cond, newArgs
}