gorm

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 10, 2026 License: MIT Imports: 32 Imported by: 0

README

Gorm

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewGormLogger

func NewGormLogger(l *log.Helper) logger.Interface

func RegisterMigrateModel

func RegisterMigrateModel(model interface{})

RegisterMigrateModel 注册用于数据库迁移的数据库模型

func RegisterMigrateModels

func RegisterMigrateModels(models ...interface{})

RegisterMigrateModels 注册用于数据库迁移的数据库模型

Types

type Client

type Client struct {
	*gorm.DB
	// contains filtered or unexported fields
}

Client GORM 客户端

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient 创建 GORM 客户端

func (*Client) Use

func (c *Client) Use(m Mixin)

Use 注册 GORM Mixin 插件

type CountOptions

type CountOptions struct {
	// Distinct 指定要去重的字段(比如 "user_id")
	Distinct string
	// Scopes 额外的自定义 scope,按顺序应用
	Scopes []func(*gorm.DB) *gorm.DB
	// Timeout 为查询超时时间(0 表示不设置超时)
	Timeout time.Duration
}

CountOptions 为扩展的计数选项

type GetMigrateModelsFunc

type GetMigrateModelsFunc func() []interface{}

type Mixin

type Mixin func(*gorm.DB) error

type Option

type Option func(*Client)

func WithAfterOpen

func WithAfterOpen(fn func(*gorm.DB) error) Option

WithAfterOpen 在建立 gorm.DB 之后执行的回调(可用于初始化指标、注册事件等)

func WithAutoMigrate

func WithAutoMigrate(models ...interface{}) Option

WithAutoMigrate 将 AutoMigrate 封装为 mixin,在 NewClient 时自动执行

func WithBeforeOpen

func WithBeforeOpen(fn func(*gorm.DB) error) Option

WithBeforeOpen 在建立 gorm.DB 之前执行的回调(可用于修改 DSN、日志等)

func WithConfigStruct

func WithConfigStruct(cfg interface{}) Option

WithConfigStruct 注入任意配置结构体(例如从 config 解码后的结构)

func WithConnMaxLifetime

func WithConnMaxLifetime(connMaxLifetime time.Duration) Option

func WithContext

func WithContext(ctx context.Context) Option

WithContext 将 context 注入 Client

func WithDSN

func WithDSN(dsn string) Option

func WithDriverName

func WithDriverName(name string) Option

func WithEnableDbResolver

func WithEnableDbResolver(enable bool) Option

func WithEnableMetrics

func WithEnableMetrics(enable bool) Option

func WithEnableMigrate

func WithEnableMigrate(enable bool) Option

func WithEnableTrace

func WithEnableTrace(enable bool) Option

func WithEnvPrefix

func WithEnvPrefix(prefix string) Option

WithEnvPrefix 指定从环境变量读取配置时的前缀(可在 NewClient 中解析)

func WithGetMigrateModels

func WithGetMigrateModels(fn GetMigrateModelsFunc) Option

WithGetMigrateModels 注入一个返回迁移模型的函数,兼容内部注册的 getMigrateModels()

func WithGormConfig

func WithGormConfig(cfg *gorm.Config) Option

func WithGormDB

func WithGormDB(db *gorm.DB) Option

func WithLogger

func WithLogger(l *log.Helper) Option

func WithMaxIdleConns

func WithMaxIdleConns(maxIdleConns int) Option

func WithMaxOpenConns

func WithMaxOpenConns(maxOpenConns int) Option

func WithMixin

func WithMixin(m Mixin) Option

WithMixin 将单个 mixin 转换为 Option

func WithMixins

func WithMixins(ms ...Mixin) Option

WithMixins 批量添加 mixin

func WithPrometheusConfig

func WithPrometheusConfig(cfg prometheus.Config) Option

func WithPrometheusDbName

func WithPrometheusDbName(dbName string) Option

func WithPrometheusHTTPServerPort

func WithPrometheusHTTPServerPort(httpServerPort uint32) Option

func WithPrometheusLabels

func WithPrometheusLabels(labels map[string]string) Option

func WithPrometheusPushAddr

func WithPrometheusPushAddr(pushAddr string) Option

func WithPrometheusPushAuth

func WithPrometheusPushAuth(user, password string) Option

func WithPrometheusRefreshInterval

func WithPrometheusRefreshInterval(refreshInterval uint32) Option

func WithPrometheusStartServer

func WithPrometheusStartServer(startServer bool) Option

func WithRawOptions

func WithRawOptions(m RawOptions) Option

WithRawOptions 注入任意键值参数供 Client 或 mixin 使用

func WithReplicaDsns

func WithReplicaDsns(dsn []string) Option

func WithTracerProvider

func WithTracerProvider(provider trace.TracerProvider) Option

func WithTracingAttributes

func WithTracingAttributes(attrs ...attribute.KeyValue) Option

func WithTracingDBSystem

func WithTracingDBSystem(name string) Option

func WithTracingOptions

func WithTracingOptions(opts ...tracing.Option) Option

func WithTracingWithoutMetrics

func WithTracingWithoutMetrics() Option

func WithTracingWithoutServerAddress

func WithTracingWithoutServerAddress() Option

type PagingResult

type PagingResult[E any] struct {
	Items []*E   `json:"items"`
	Total uint64 `json:"total"`
}

PagingResult 通用分页返回

type RawOptions

type RawOptions map[string]interface{}

type Repository

type Repository[DTO any, ENTITY any] struct {
	// contains filtered or unexported fields
}

Repository GORM 仓库,包含常用的 CRUD 方法

func NewRepository

func NewRepository[DTO any, ENTITY any](mapper *mapper.CopierMapper[DTO, ENTITY]) *Repository[DTO, ENTITY]

func (*Repository[DTO, ENTITY]) BatchCreate

func (r *Repository[DTO, ENTITY]) BatchCreate(ctx context.Context, db *gorm.DB, dtos []*DTO, viewMask *fieldmaskpb.FieldMask) ([]*DTO, error)

BatchCreate 批量创建记录,返回创建后的 DTO 列表 将此方法添加到 `gorm/repository.go` 中的 Repository 定义下

func (*Repository[DTO, ENTITY]) Count

func (r *Repository[DTO, ENTITY]) Count(ctx context.Context, db *gorm.DB, whereSelectors []func(*gorm.DB) *gorm.DB) (int64, error)

Count 使用 whereSelectors 计算符合条件的记录数

func (*Repository[DTO, ENTITY]) CountWithOptions

func (r *Repository[DTO, ENTITY]) CountWithOptions(ctx context.Context, db *gorm.DB, whereSelectors []func(*gorm.DB) *gorm.DB, opts *CountOptions) (int64, error)

CountWithOptions 使用可选参数执行计数,返回 int64(更通用) 保持原有 whereSelectors 参数风格,额外行为由 opts 控制

func (*Repository[DTO, ENTITY]) Create

func (r *Repository[DTO, ENTITY]) Create(ctx context.Context, db *gorm.DB, dto *DTO, viewMask *fieldmaskpb.FieldMask) (*DTO, error)

Create 在数据库中创建一条记录,返回创建后的 DTO 示例调用: `dto, err := q.Create(ctx, db, dto, viewMask)`

func (*Repository[DTO, ENTITY]) CreateX

func (r *Repository[DTO, ENTITY]) CreateX(ctx context.Context, db *gorm.DB, dto *DTO, viewMask *fieldmaskpb.FieldMask) (int64, error)

CreateX 使用传入的 db 创建记录,支持 viewMask 指定插入字段,返回受影响行数 示例调用: `rows, err := q.CreateX(ctx, db, dto, viewMask)`

func (*Repository[DTO, ENTITY]) CreateXWithFilters

func (r *Repository[DTO, ENTITY]) CreateXWithFilters(ctx context.Context, db *gorm.DB, whereSelectors []func(*gorm.DB) *gorm.DB, dto *DTO, viewMask *fieldmaskpb.FieldMask) (int64, error)

CreateXWithFilters 接受 whereSelectors 并在内部应用到查询 DB,然后执行创建,返回受影响行数 示例调用:构造 selectors 后调用: `rows, err := q.CreateXWithFilters(ctx, db, whereSelectors, dto, viewMask)`

func (*Repository[DTO, ENTITY]) Delete

func (r *Repository[DTO, ENTITY]) Delete(ctx context.Context, db *gorm.DB, notSoftDelete bool) (int64, error)

Delete 使用传入的 db(可包含 Where)删除记录 示例调用: `rows, err := q.Delete(ctx, db.Where("id = ?", id))`

func (*Repository[DTO, ENTITY]) DeleteWithFilters

func (r *Repository[DTO, ENTITY]) DeleteWithFilters(ctx context.Context, db *gorm.DB, whereSelectors []func(*gorm.DB) *gorm.DB) (int64, error)

DeleteWithFilters 接受 whereSelectors 并在内部应用到查询 DB,然后执行删除 示例调用:构造 selectors 后调用: `rows, err := q.DeleteWithFilters(ctx, db, whereSelectors)`

func (*Repository[DTO, ENTITY]) Exists

func (r *Repository[DTO, ENTITY]) Exists(ctx context.Context, db *gorm.DB) (bool, error)

Exists 使用传入的 db(可包含 Where)检查是否存在记录 示例调用: `exists, err := q.Exists(ctx, db.Where("id = ?", id))`

func (*Repository[DTO, ENTITY]) ExistsWithFilters

func (r *Repository[DTO, ENTITY]) ExistsWithFilters(ctx context.Context, db *gorm.DB, whereSelectors []func(*gorm.DB) *gorm.DB) (bool, error)

ExistsWithFilters 接受 whereSelectors 并在内部应用到查询 DB,然后检查是否存在记录 示例调用:构造 selectors 后调用: `exists, err := q.ExistsWithFilters(ctx, db, whereSelectors)`

func (*Repository[DTO, ENTITY]) Get

func (r *Repository[DTO, ENTITY]) Get(ctx context.Context, db *gorm.DB, viewMask *fieldmaskpb.FieldMask) (*DTO, error)

Get 根据查询条件获取单条记录 示例调用: `dto, err := q.Get(ctx, db.Where("id = ?", id), nil)`

func (*Repository[DTO, ENTITY]) GetWithFilters

func (r *Repository[DTO, ENTITY]) GetWithFilters(ctx context.Context, db *gorm.DB, whereSelectors []func(*gorm.DB) *gorm.DB, viewMask *fieldmaskpb.FieldMask) (*DTO, error)

GetWithFilters 接受 whereSelectors 并在内部应用到查询 DB,然后执行原有逻辑 示例调用:使用 q.queryStringFilter 等构造 selectors 后调用新方法 whereSelectors, _ := q.queryStringFilter.BuildSelectors(req.GetQuery(), req.GetOrQuery()) dto, err := q.GetWithFilters(ctx, db, whereSelectors, viewMask)

func (*Repository[DTO, ENTITY]) ListWithPagination

func (r *Repository[DTO, ENTITY]) ListWithPagination(ctx context.Context, db *gorm.DB, req *paginationV1.PaginationRequest) (*PagingResult[DTO], error)

ListWithPagination 使用 PaginationRequest 查询列表(接收 *gorm.DB)

func (*Repository[DTO, ENTITY]) ListWithPaging

func (r *Repository[DTO, ENTITY]) ListWithPaging(ctx context.Context, db *gorm.DB, req *paginationV1.PagingRequest) (*PagingResult[DTO], error)

ListWithPaging 使用 PagingRequest 查询列表(接收 *gorm.DB)

func (*Repository[DTO, ENTITY]) Only

func (r *Repository[DTO, ENTITY]) Only(ctx context.Context, db *gorm.DB, viewMask *fieldmaskpb.FieldMask) (*DTO, error)

Only alias

func (*Repository[DTO, ENTITY]) SoftDelete

func (r *Repository[DTO, ENTITY]) SoftDelete(ctx context.Context, db *gorm.DB) (int64, error)

SoftDelete 对符合 whereSelectors 的记录执行软删除 whereSelectors: 应用到查询的 where scopes(按顺序) doSoftDeleteFunc: 可选回调,接收当前 *gorm.DB 并执行自定义更新操作(应返回执行后的 *gorm.DB) 当 doSoftDeleteFunc 为 nil 时,默认更新 deleted_at 字段为当前时间

func (*Repository[DTO, ENTITY]) Update

func (r *Repository[DTO, ENTITY]) Update(ctx context.Context, db *gorm.DB, dto *DTO, updateMask *fieldmaskpb.FieldMask) (*DTO, error)

Update 使用传入的 db(可包含 Where)更新记录,支持 updateMask 指定更新字段 示例调用: `dto, err := q.Update(ctx, db.Where("id = ?", id), dto, updateMask)`

func (*Repository[DTO, ENTITY]) UpdateWithFilters

func (r *Repository[DTO, ENTITY]) UpdateWithFilters(ctx context.Context, db *gorm.DB, whereSelectors []func(*gorm.DB) *gorm.DB, dto *DTO, updateMask *fieldmaskpb.FieldMask) (*DTO, error)

UpdateWithFilters 接受 whereSelectors 并在内部应用到查询 DB,然后执行更新 示例调用:构造 selectors 后调用: `dto, err := q.UpdateWithFilters(ctx, db, whereSelectors, dto, updateMask)`

func (*Repository[DTO, ENTITY]) UpdateX

func (r *Repository[DTO, ENTITY]) UpdateX(ctx context.Context, db *gorm.DB, dto *DTO, updateMask *fieldmaskpb.FieldMask) (int64, error)

UpdateX 使用传入的 db(可包含 Where)更新记录,支持 updateMask 指定更新字段,返回受影响行数 示例调用: `rows, err := q.UpdateX(ctx, db.Where("id = ?", id), dto, updateMask)`

func (*Repository[DTO, ENTITY]) UpdateXWithFilters

func (r *Repository[DTO, ENTITY]) UpdateXWithFilters(ctx context.Context, db *gorm.DB, whereSelectors []func(*gorm.DB) *gorm.DB, dto *DTO, updateMask *fieldmaskpb.FieldMask) (int64, error)

UpdateXWithFilters 接受 whereSelectors 并在内部应用到查询 DB,然后执行更新,返回受影响行数 示例调用:构造 selectors 后调用: `rows, err := q.UpdateXWithFilters(ctx, db, whereSelectors, dto, updateMask)`

func (*Repository[DTO, ENTITY]) Upsert

func (r *Repository[DTO, ENTITY]) Upsert(ctx context.Context, db *gorm.DB, dto *DTO, updateMask *fieldmaskpb.FieldMask) (*DTO, error)

Upsert 使用传入的 db(可包含 Where/其他 scope)执行插入或冲突更新,支持 updateMask 指定冲突时更新的字段 示例调用: `dto, err := q.Upsert(ctx, db, dto, updateMask)`

func (*Repository[DTO, ENTITY]) UpsertWithFilters

func (r *Repository[DTO, ENTITY]) UpsertWithFilters(ctx context.Context, db *gorm.DB, whereSelectors []func(*gorm.DB) *gorm.DB, dto *DTO, updateMask *fieldmaskpb.FieldMask) (*DTO, error)

UpsertWithFilters 接受 whereSelectors 并在内部应用到查询 DB,然后执行 upsert,支持 updateMask 指定冲突时更新的字段 示例调用:构造 selectors 后调用: `dto, err := q.UpsertWithFilters(ctx, db, whereSelectors, dto, updateMask)`

func (*Repository[DTO, ENTITY]) UpsertX

func (r *Repository[DTO, ENTITY]) UpsertX(ctx context.Context, db *gorm.DB, dto *DTO, updateMask *fieldmaskpb.FieldMask) (int64, error)

UpsertX 使用传入的 db(可包含 Where/其他 scope)执行插入或冲突更新,支持 updateMask 指定冲突时更新的字段,返回受影响行数 示例调用: `rows, err := q.UpsertX(ctx, db, dto, updateMask)`

func (*Repository[DTO, ENTITY]) UpsertXWithFilters

func (r *Repository[DTO, ENTITY]) UpsertXWithFilters(ctx context.Context, db *gorm.DB, whereSelectors []func(*gorm.DB) *gorm.DB, dto *DTO, updateMask *fieldmaskpb.FieldMask) (int64, error)

UpsertXWithFilters 接受 whereSelectors 并在内部应用到查询 DB,然后执行 upsert,支持 updateMask 指定冲突时更新的字段,返回受影响行数 示例调用:构造 selectors 后调用: `rows, err := q.UpsertXWithFilters(ctx, db, whereSelectors, dto, updateMask)`

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL