Documentation
¶
Overview ¶
Package store 提供基于 GORM 的通用 CRUD 仓储基类: 开箱即用的分页、字段过滤、排序校验与软删除约定。
使用示例:
type User struct {
gorm.Model
Name string
}
repo := store.NewRepository[model.User](db)
repo.Create(ctx, &user)
page, err := repo.List(ctx, store.Query{Page: 1, PageSize: 20, Filters: map[string]any{"name": "alice"}})
过滤条件为等值匹配,字段名必须满足列名规范,否则返回错误(fail-closed), 避免 SQL 注入。排序字段同样受白名单校验。
Index ¶
- Constants
- Variables
- type PageResult
- type Query
- type Repository
- func (r *Repository[T]) Count(ctx context.Context, q Query) (int64, error)
- func (r *Repository[T]) Create(ctx context.Context, entity *T) error
- func (r *Repository[T]) Delete(ctx context.Context, id uint) error
- func (r *Repository[T]) GetByID(ctx context.Context, id uint) (*T, error)
- func (r *Repository[T]) List(ctx context.Context, q Query) (*PageResult[T], error)
- func (r *Repository[T]) Update(ctx context.Context, entity *T) error
Constants ¶
const ( // DefaultPageSize 未指定分页大小时每页返回的记录数 DefaultPageSize = 20 // MaxPageSize 单页允许的最大记录数,超出会被截断 MaxPageSize = 100 )
默认分页参数.
Variables ¶
var ErrInvalidField = errors.New("store: invalid field name")
ErrInvalidField 表示过滤/排序字段名不合法(fail-closed,拒绝执行).
var ErrInvalidSort = errors.New("store: invalid sort direction")
ErrInvalidSort 表示排序方向不合法.
var ErrNotFound = gorm.ErrRecordNotFound
ErrNotFound 表示按条件未查询到记录.
Functions ¶
This section is empty.
Types ¶
type PageResult ¶
type PageResult[T any] struct { // Items 当前页记录 Items []T // Total 过滤条件下的记录总数 Total int64 // Page 当前页码(归一化后) Page int // PageSize 每页记录数(归一化后) PageSize int }
PageResult 分页查询结果.
type Query ¶
type Query struct {
// Page 页码,从 1 开始,默认 1
Page int
// PageSize 每页记录数,默认 DefaultPageSize,最大 MaxPageSize
PageSize int
// Sort 排序字段,可带 " asc"/" desc" 方向后缀,如 "created_at desc";默认按 id 倒序
Sort string
// Filters 等值过滤条件,键为数据库列名(如 "name" 或 "users.name")
Filters map[string]any
}
Query 列表查询的分页与过滤参数.
type Repository ¶
type Repository[T any] struct { // contains filtered or unexported fields }
Repository 基于 GORM 的泛型 CRUD 仓储基类.
func NewRepository ¶
func NewRepository[T any](db *gorm.DB) (*Repository[T], error)
NewRepository 创建仓储实例,db 不能为 nil.
func (*Repository[T]) Create ¶
func (r *Repository[T]) Create(ctx context.Context, entity *T) error
Create 插入一条记录.
func (*Repository[T]) Delete ¶
func (r *Repository[T]) Delete(ctx context.Context, id uint) error
Delete 按主键删除。模型包含 gorm.DeletedAt 字段时执行软删除,否则物理删除.
func (*Repository[T]) GetByID ¶
func (r *Repository[T]) GetByID(ctx context.Context, id uint) (*T, error)
GetByID 按主键查询,未找到时返回 ErrNotFound.
func (*Repository[T]) List ¶
func (r *Repository[T]) List(ctx context.Context, q Query) (*PageResult[T], error)
List 分页查询。过滤、排序、分页一并应用;items 为空时返回空切片而非 nil.