Documentation
¶
Overview ¶
Package gormhelper provides a generic repository pattern implementation for GORM. It offers a type-safe wrapper around GORM operations with support for transactions, scoped queries, pagination, and common CRUD operations.
Index ¶
- Variables
- type PageResult
- type Repo
- func (r *Repo[T]) BatchInsert(ctx context.Context, tx *gorm.DB, ents []*T, batchSize ...int) error
- func (r *Repo[T]) Count(ctx context.Context, scopes ...Scope) (int64, error)
- func (r *Repo[T]) Create(ctx context.Context, tx *gorm.DB, ent *T) error
- func (r *Repo[T]) Delete(ctx context.Context, tx *gorm.DB, scopes ...Scope) error
- func (r *Repo[T]) Exists(ctx context.Context, scopes ...Scope) (bool, error)
- func (r *Repo[T]) FindForUpdate(ctx context.Context, tx *gorm.DB, scopes ...Scope) ([]T, error)
- func (r *Repo[T]) First(ctx context.Context, scopes ...Scope) (T, error)
- func (r *Repo[T]) FirstForUpdate(ctx context.Context, tx *gorm.DB, scopes ...Scope) (T, error)
- func (r *Repo[T]) List(ctx context.Context, scopes ...Scope) ([]T, error)
- func (r *Repo[T]) Page(ctx context.Context, page, pageSize int, scopes ...Scope) (PageResult[T], error)
- func (r *Repo[T]) Transact(ctx context.Context, fn func(ctx context.Context, tx *gorm.DB) error) error
- func (r *Repo[T]) Update(ctx context.Context, tx *gorm.DB, ent *T) error
- type Scope
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidType is returned when the generic type T is not a struct type. ErrInvalidType = errors.New("generic type must be a struct type") // ErrNotFound is returned when a requested record is not found. ErrNotFound = errors.New("not found") // ErrTxRequired is returned when a transaction is required but not provided. ErrTxRequired = errors.New("tx is required") // ErrNilSchema is returned when GORM schema parsing results in a nil schema. ErrNilSchema = errors.New("nil schema") // ErrDangerous is returned when attempting potentially dangerous operations // like deleting without conditions. ErrDangerous = errors.New("dangerous operation is prohibited") )
Common errors returned by repository operations.
Functions ¶
This section is empty.
Types ¶
type PageResult ¶
type PageResult[T any] struct { Items []T `json:"items"` // The items in the current page Total int64 `json:"total"` // Total number of items across all pages Page int `json:"page"` // Current page number (1-based) PageSize int `json:"page_size"` // Number of items per page HasNext bool `json:"has_next"` // Whether there are more pages available }
PageResult represents the result of a paginated query.
type Repo ¶
type Repo[T any] struct { // contains filtered or unexported fields }
Repo is a generic repository that provides common database operations for entities of type T. It wraps a GORM database instance and provides type-safe methods for CRUD operations, querying, and transaction handling.
func NewRepo ¶
NewRepo creates a new generic repository instance for type T. It validates that T is a struct type and parses the GORM schema. Returns an error if T is not a valid struct type or schema parsing fails.
func (*Repo[T]) BatchInsert ¶
BatchInsert performs a batch insert operation for multiple entities. If tx is provided, the operation is performed within that transaction. The optional batchSize parameter controls how many records are inserted in each batch. If not specified or zero, defaults to 1000 records per batch.
func (*Repo[T]) Create ¶
Create inserts a new entity into the database. If tx is provided, the operation is performed within that transaction. Otherwise, it uses the repository's default database connection.
func (*Repo[T]) Delete ¶
Delete removes records from the database based on the provided conditions. At least one scope must be provided to prevent accidental deletion of all records. If tx is provided, the operation is performed within that transaction.
func (*Repo[T]) Exists ¶
Exists checks whether any record matching the provided scopes exists. Returns true if at least one record exists, false otherwise.
func (*Repo[T]) FindForUpdate ¶
FindForUpdate retrieves all records that match the provided scopes with a SELECT FOR UPDATE lock. This method requires a transaction to be provided. Returns ErrTxRequired if no transaction is provided.
func (*Repo[T]) First ¶
First retrieves the first record that matches the provided scopes. Returns ErrNotFound if no record is found.
func (*Repo[T]) FirstForUpdate ¶
FirstForUpdate retrieves the first record that matches the provided scopes with a SELECT FOR UPDATE lock. This method requires a transaction to be provided. Returns ErrNotFound if no record is found, ErrTxRequired if no transaction is provided.
func (*Repo[T]) List ¶
List retrieves all records that match the provided scopes. Consider using Limit and Order scopes to control the result set size and ordering.
func (*Repo[T]) Page ¶
func (r *Repo[T]) Page(ctx context.Context, page, pageSize int, scopes ...Scope) (PageResult[T], error)
Page retrieves a paginated result set based on the provided scopes. Page numbers are 1-based. If page <= 0, defaults to 1. If pageSize <= 0, defaults to 20. Maximum pageSize is capped at 1000.
func (*Repo[T]) Transact ¶
func (r *Repo[T]) Transact(ctx context.Context, fn func(ctx context.Context, tx *gorm.DB) error) error
Transact executes the provided function within a database transaction. If the function returns an error, the transaction is rolled back. Otherwise, the transaction is committed.
type Scope ¶
Scope represents a function that can modify a GORM database query. Scopes can be chained together to build complex queries in a composable way.
func OnlyDeleted ¶
func OnlyDeleted() Scope
OnlyDeleted creates a scope that returns only soft-deleted records.
func Where ¶
Where creates a scope that adds a WHERE clause to the query. It accepts the same parameters as GORM's Where method.
func WhereEq ¶
WhereEq creates a scope that adds WHERE clauses for exact matches using a map of column names to values.
func WithDeleted ¶
func WithDeleted() Scope
WithDeleted creates a scope that includes soft-deleted records in the query. This is equivalent to GORM's Unscoped method.