sql-builder/db/add_sql.go

66 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package db
import (
"fmt"
"reflect"
"strings"
)
func (s *SqlBuilder[T]) SetSql(sql string) {
s.Sql = sql
}
// 如果添加的条件是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)
s.Opts.conditions = append(s.Opts.conditions, cond)
s.Opts.args = append(s.Opts.args, args...)
s.buildCondition(cond)
}
func (s *SqlBuilder[T]) Selects(selects ...string) {
s.Opts.selects = append(s.Opts.selects, selects...)
s.buildSelect(selects...)
}
func (s *SqlBuilder[T]) Groups(groups ...string) {
s.Opts.groups = append(s.Opts.groups, groups...)
s.buildGroup(groups...)
}
func (s *SqlBuilder[T]) Orders(orders ...string) {
s.Opts.orders = append(s.Opts.orders, orders...)
s.buildOrder(orders...)
}
func (s *SqlBuilder[T]) Partitions(partitions ...string) {
s.Opts.partitions = append(s.Opts.partitions, partitions...)
s.buildPartition(partitions...)
}
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
}