Go 代码中 SQL 的 OR 语句优先级问题修复
这段代码生成的 SQL 中的 OR 语句可能会出现问题,因为没有括号来明确 OR 的优先级。在这种情况下,AND 操作符的优先级会高于 OR 操作符,可能会导致查询结果不符合预期。
修复后的代码如下:
func (p postServiceImpl) Page(ctx context.Context, postQuery param.PostQuery) ([]*entity.Post, int64, error) {
if postQuery.PageNum < 0 || postQuery.PageSize <= 0 {
return nil, 0, xerr.BadParam.New("").WithStatus(xerr.StatusBadRequest).WithMsg("Paging parameter error")
}
postDAL := dal.GetQueryByCtx(ctx).Post
postCategoryDAL := dal.GetQueryByCtx(ctx).PostCategory
postDo := postDAL.WithContext(ctx).Debug().Where(postDAL.Type.Eq(consts.PostTypePost))
err := BuildSort(postQuery.Sort, &postDAL, &postDo)
if err != nil {
return nil, 0, err
}
if postQuery.Keyword != nil {
postDo.Where(postDAL.Title.Like('%' + *postQuery.Keyword + '%').Or(postDAL.OriginalContent.Like('%' + *postQuery.Keyword + '%')))
}
if postQuery.WithPassword != nil && !*postQuery.WithPassword {
postDo.Where(postDAL.Password.Neq(""))
}
if len(postQuery.Statuses) > 0 {
statuesValue := make([]driver.Valuer, len(postQuery.Statuses))
for i, status := range postQuery.Statuses {
statuesValue[i] = driver.Valuer(status)
}
postDo.Where(postDAL.Status.In(statuesValue...))
}
if postQuery.CategoryID != nil {
postDo.Join(&entity.PostCategory{}, postDAL.ID.EqCol(postCategoryDAL.PostID)).Where(postCategoryDAL.CategoryID.Eq(*postQuery.CategoryID))
}
posts, totalCount, err := postDo.FindByPage(postQuery.PageNum*postQuery.PageSize, postQuery.PageSize)
if err != nil {
return nil, 0, WrapDBErr(err)
}
return posts, totalCount, nil
}
修复后的代码将 OR 操作符放在括号中,以确保其优先级高于 AND 操作符。
原文地址: https://www.cveoy.top/t/topic/nPtf 著作权归作者所有。请勿转载和采集!