92 lines
1.9 KiB
Go
92 lines
1.9 KiB
Go
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("不存在")
|
||
}
|
||
}
|