light-core/pkg/mySql/QueryManager.go
2024-12-17 22:47:16 +08:00

92 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package mySql
import (
"errors"
"gorm.io/gorm"
"reflect"
)
// 因为有大量的是简单的通过where查询一条数据的例如查询某个用户的资料所以封装这个工具类简化操作用法与query保持一致
type QueryManager struct {
tableName string
wheres []*QueryManagerWhere
errorText string
error error
}
type QueryManagerWhere struct {
colName string
value interface{}
emptyCheck bool
}
func NewQueryManager(tableName string) *QueryManager {
return &QueryManager{
tableName: tableName,
wheres: make([]*QueryManagerWhere, 0),
}
}
func (t *QueryManager) SetErrorText(text string) *QueryManager {
t.errorText = text
return t
}
func (t *QueryManager) Where(colName string, value interface{}) *QueryManager {
t.wheres = append(t.wheres, &QueryManagerWhere{
colName: colName,
value: value,
emptyCheck: true,
})
return t
}
func (t *QueryManager) WhereRow(colName string, value interface{}, emptyCheck bool) *QueryManager {
t.wheres = append(t.wheres, &QueryManagerWhere{
colName: colName,
value: value,
emptyCheck: emptyCheck,
})
return t
}
func (t *QueryManager) Take(data interface{}) error {
if len(t.wheres) == 0 {
return errors.New("not where")
}
for colName := range t.wheres {
if isBlank(reflect.ValueOf(t.wheres[colName])) {
//如果是空值
return t.getEmptyError()
}
}
query := NewQuery(t.tableName)
for _, where := range t.wheres {
if where.emptyCheck {
//检查空值
if isBlank(reflect.ValueOf(where.value)) {
return t.getEmptyError()
}
}
query.Where(where.colName, where.value)
}
err := query.Take(data)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return t.getEmptyError()
}
}
return err
}
func (t *QueryManager) getEmptyError() error {
if t.errorText != "" {
return errors.New(t.errorText)
} else {
return errors.New("不存在")
}
}