You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.4 KiB
57 lines
1.4 KiB
2 years ago
|
package ormutil
|
||
2 years ago
|
|
||
|
import (
|
||
2 years ago
|
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
|
||
2 years ago
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
2 years ago
|
func GormPage[E any](db *gorm.DB, pageNumber, showNumber int32) (uint32, []*E, error) {
|
||
2 years ago
|
var count int64
|
||
2 years ago
|
if err := db.Count(&count).Error; err != nil {
|
||
2 years ago
|
return 0, nil, utils.Wrap(err, "")
|
||
|
}
|
||
|
var es []*E
|
||
|
if err := db.Limit(int(showNumber)).Offset(int(pageNumber * showNumber)).Find(&es).Error; err != nil {
|
||
|
return 0, nil, utils.Wrap(err, "")
|
||
|
}
|
||
2 years ago
|
return uint32(count), es, nil
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
func GormSearch[E any](db *gorm.DB, fields []string, value string, pageNumber, showNumber int32) (uint32, []*E, error) {
|
||
2 years ago
|
if len(fields) > 0 && value != "" {
|
||
|
value = "%" + value + "%"
|
||
|
if len(fields) == 1 {
|
||
|
db = db.Where(fields[0]+" like ?", value)
|
||
|
} else {
|
||
|
t := db
|
||
|
for _, field := range fields {
|
||
|
t = t.Or(field+" like ?", value)
|
||
|
}
|
||
|
db = db.Where(t)
|
||
|
}
|
||
2 years ago
|
}
|
||
2 years ago
|
return GormPage[E](db, pageNumber, showNumber)
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
2 years ago
|
func GormIn[E any](db **gorm.DB, field string, es []E) {
|
||
2 years ago
|
if len(es) == 0 {
|
||
|
return
|
||
|
}
|
||
|
*db = (*db).Where(field+" in (?)", es)
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
func MapCount(db *gorm.DB, field string) (map[string]uint32, error) {
|
||
2 years ago
|
var items []struct {
|
||
|
ID string `gorm:"column:id"`
|
||
|
Count uint32 `gorm:"column:count"`
|
||
|
}
|
||
|
if err := db.Select(field + " as id, count(1) as count").Group(field).Find(&items).Error; err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
m := make(map[string]uint32)
|
||
|
for _, item := range items {
|
||
|
m[item.ID] = item.Count
|
||
|
}
|
||
|
return m, nil
|
||
|
}
|