Files
go-admin/common/actions/index.go
T
zhangwenjian ea2d807071 fix🐛: give queries the request's context, not the pooled gin.Context
WithContextDb and the five CRUD actions passed the *gin.Context itself
to GORM as the query's context. database/sql watches the context of a
query that returns rows inside a transaction from a goroutine of its
own, which can still read it after the handler returns - and gin hands
that Context to the next request as soon as the handler returns. GORM
wraps every write in a transaction, and an INSERT on SQLite or
PostgreSQL returns the new key as a row, so any write raced with the
next request's reset. The race detector reports it on the second of
two sequential requests.

They now pass c.Request.Context(), which belongs to one request only
and is cancelled when its client goes away.
2026-09-27 20:45:45 +08:00

59 lines
1.4 KiB
Go

package actions
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
log "github.com/go-admin-team/go-admin-core/v2/logger"
"github.com/go-admin-team/go-admin-core/v2/response"
"github.com/go-admin-team/go-admin-core/v2/sdk/pkg"
"gorm.io/gorm"
"go-admin/common/dto"
"go-admin/common/models"
)
// IndexAction 通用查询动作
func IndexAction(m models.ActiveRecord, d dto.Index, f func() interface{}) gin.HandlerFunc {
return func(c *gin.Context) {
db, err := pkg.GetOrm(c)
if err != nil {
log.Error(err)
return
}
msgID := pkg.GenerateMsgIDFromContext(c)
list := f()
object := m.Generate()
req := d.Generate()
var count int64
//查询列表
err = req.Bind(c)
if err != nil {
response.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
return
}
//数据权限检查
p := GetPermissionFromContext(c)
err = db.WithContext(c.Request.Context()).Model(object).
Scopes(
dto.MakeCondition(req.GetNeedSearch()),
dto.Paginate(req.GetPageSize(), req.GetPageIndex()),
Permission(object.TableName(), p),
).
Find(list).Limit(-1).Offset(-1).
Count(&count).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
log.Errorf("MsgID[%s] Index error: %s", msgID, err)
response.Error(c, 500, err, "查询失败")
return
}
response.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
c.Next()
}
}