Files
go-sms-V2/internal/repository/mysql/base.go
T

115 lines
3.3 KiB
Go

// Package mysql MySQL 数据访问层(Day 11):
// BaseDAO 提供泛型 CRUD + 软删除;具体 DAO 以类型实例化复用。
// 连接池配置在 Open(Day 14 迁移工具接入时由 app 启动器调用)。
package mysql
import (
"context"
"errors"
"fmt"
"gorm.io/gorm"
)
// ErrNotFound 目标记录不存在(含已软删)。
var ErrNotFound = errors.New("mysql: 记录不存在")
// BaseDAO 通用数据访问对象。
// T 须为指针类型且含主键字段(entity.Model / LogModel / SnowflakeModel)。
type BaseDAO[T any] struct {
db *gorm.DB
}
// NewBaseDAO 构造;db 为已配置好连接池的 *gorm.DB。
func NewBaseDAO[T any](db *gorm.DB) *BaseDAO[T] {
return &BaseDAO[T]{db: db}
}
// DB 暴露底层 gorm.DB(事务/复杂查询场景)。
func (d *BaseDAO[T]) DB() *gorm.DB { return d.db }
// Create 插入记录(零值主键由数据库/调用方生成)。
func (d *BaseDAO[T]) Create(ctx context.Context, entity T) error {
return d.db.WithContext(ctx).Create(entity).Error
}
// CreateBatch 批量插入。
func (d *BaseDAO[T]) CreateBatch(ctx context.Context, entities []T, batchSize int) error {
if batchSize <= 0 {
batchSize = 500
}
return d.db.WithContext(ctx).CreateInBatches(entities, batchSize).Error
}
// Update 全量保存(按主键;零值字段也会写入,需部分更新用 DB() 定制)。
func (d *BaseDAO[T]) Update(ctx context.Context, entity T) error {
res := d.db.WithContext(ctx).Save(entity)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrNotFound
}
return nil
}
// Updates 按主键部分更新(白名单字段映射)。
func (d *BaseDAO[T]) Updates(ctx context.Context, id int64, fields map[string]any) error {
res := d.db.WithContext(ctx).Model(new(T)).Where("id = ?", id).Updates(fields)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return ErrNotFound
}
return nil
}
// GetByID 主键查询(软删记录自动过滤)。
func (d *BaseDAO[T]) GetByID(ctx context.Context, id int64) (T, error) {
var out T
if err := d.db.WithContext(ctx).First(&out, "id = ?", id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return out, fmt.Errorf("%w: id=%d", ErrNotFound, id)
}
return out, err
}
return out, nil
}
// List 分页列表:conds 为 Where 条件(如 "status = ?", 1),order 为排序子句。
// 返回 (记录, 总数, 错误);总数基于同一条件(不含分页)。
func (d *BaseDAO[T]) List(ctx context.Context, offset, limit int, order string, conds ...any) ([]T, int64, error) {
if limit <= 0 || limit > 1000 {
limit = 20
}
query := d.db.WithContext(ctx).Model(new(T))
if len(conds) > 0 {
query = query.Where(conds[0], conds[1:]...)
}
var total int64
if err := query.Count(&total).Error; err != nil {
return nil, 0, err
}
if order != "" {
query = query.Order(order) // 调用方负责排序子句合法性
}
var out []T
if err := query.Offset(offset).Limit(limit).Find(&out).Error; err != nil {
return nil, 0, err
}
return out, total, nil
}
// Delete 软删除(仅含 DeletedAt 的模型生效;Log 类模型将硬删,调用方注意)。
func (d *BaseDAO[T]) Delete(ctx context.Context, id int64) error {
res := d.db.WithContext(ctx).Delete(new(T), "id = ?", id)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return fmt.Errorf("%w: id=%d", ErrNotFound, id)
}
return nil
}