1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
order.go 2.07 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2024-09-11 16:38 . dao 整理
package wrapper
import (
commonoption "gitee.com/h79/goutils/common/option"
"gitee.com/h79/goutils/dao/option"
"strings"
)
const (
kDesc = "DESC"
kAsc = "ASC"
)
var _ IBuilder = (*OrderBy)(nil)
// OrderBy 排序(降序(大=>小)desc, 升序(小=>大)asc
// example: "orderBy:[{"col:"create_at","desc":true}, {"col":"id","desc":false}]
//
// "orderBy:[{"col:"create_at,id","desc":true}]
type OrderBy []Column
func (ob *OrderBy) Is() bool {
return len(*ob) > 0
}
func (ob *OrderBy) Build(opts ...commonoption.Option) string {
var ii = 0
var m = 6
var full = false
var convert option.ColumnConvertFunc
commonoption.Filter(func(opt commonoption.Option) bool {
if opt.Type() == option.TypeMaxColumn {
m = opt.Value().(int)
ii++
} else if opt.Type() == option.TypeFullSql {
full = opt.Value().(bool)
ii++
} else if opt.Type() == option.TypeSqlColumnConvert {
convert = opt.Value().(option.ColumnConvertFunc)
ii++
}
return ii == 3
}, opts...)
return ob.buildOpt(full, convert, m)
}
func (ob *OrderBy) Check(filters []FField, opts ...commonoption.Option) {
length := len(*ob)
var m = option.MaxColumnExist(opts...)
if length > m { //防止多
length = m
}
cols := (*ob)[:length]
for i := range cols {
cols[i].Check(filters)
}
}
func (ob *OrderBy) buildOpt(full bool, convert option.ColumnConvertFunc, max int) string {
count := 0
builder := strings.Builder{}
for i := range *ob {
if count >= max {
//后面不要接入
break
}
if c := ob.build(&(*ob)[i], convert); len(c) > 0 {
if count == 0 {
if full {
builder.WriteString(" ORDER BY ")
}
} else if count > 0 {
builder.WriteByte(',')
}
builder.WriteString(c)
count++
}
}
return builder.String()
}
func (ob *OrderBy) build(col *Column, convert option.ColumnConvertFunc) string {
var cc = false
var builder = strings.Builder{}
if convert != nil {
cc = SqlColumn(&builder, convert(col.Column))
} else {
cc = SqlColumn(&builder, col.Column)
}
if cc && col.Desc {
builder.WriteByte(' ')
builder.WriteString(kDesc)
}
return builder.String()
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.21.21

搜索帮助