woj-server/internal/service/problem/query_fuzz.go

61 lines
1.2 KiB
Go
Raw Normal View History

2022-09-20 16:42:57 +08:00
package problem
import (
2023-07-14 21:47:11 +08:00
"git.0x7f.app/WOJ/woj-server/internal/e"
"git.0x7f.app/WOJ/woj-server/internal/model"
"go.uber.org/zap"
2022-09-26 16:13:31 +08:00
"gorm.io/gorm/clause"
2022-09-20 16:42:57 +08:00
)
type QueryData struct {
// precise
ID uint
// fuzz
Keyword string
Tag string
// common
Associations bool
ShouldEnable bool
// paging
Offset int
Limit int
Count *int64
}
func (s *service) QueryFuzz(data *QueryData) ([]*model.Problem, e.Status) {
problems := make([]*model.Problem, 0)
2023-07-15 16:19:49 +08:00
query := s.db.Get()
2023-12-27 21:30:52 +08:00
if data.Associations {
query = query.Preload(clause.Associations)
}
if data.ShouldEnable {
query = query.Where("is_enabled = true")
2022-09-20 16:42:57 +08:00
}
2023-12-27 21:30:52 +08:00
if data.Keyword != "" {
query = query.
Where(s.db.Get().Where("title LIKE ?", "%"+data.Keyword+"%").
Or("statement LIKE ?", "%"+data.Keyword+"%"))
}
2023-12-27 21:30:52 +08:00
if data.Tag != "" {
query = query.Where("EXISTS(SELECT 1 FROM unnest(tags) AS elem WHERE elem LIKE ?)", "%"+data.Tag+"%")
2023-12-27 21:30:52 +08:00
}
err := query.Order("created_at ASC").
Offset(data.Offset).Limit(data.Limit).Find(&problems).
Offset(-1).Limit(-1).Count(data.Count).
Error
2022-09-20 16:42:57 +08:00
if err != nil {
s.log.Warn("DatabaseError", zap.Error(err), zap.Any("QueryData", data))
2022-09-20 16:42:57 +08:00
return nil, e.DatabaseError
}
return problems, e.Success
}