gorm

package module
v0.0.0-...-bd7e268 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package gorm provides a GORM-based implementation of the generic repository pattern. It offers a type-safe wrapper around GORM operations with support for transactions, scoped queries, pagination, and common CRUD operations.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Limit

func Limit(n int) repository.Scope

Limit creates a scope that limits the number of returned records.

func NewRepository

func NewRepository[T any](db *gorm.DB) (repository.Repository[T], error)

NewRepository creates a new GORM 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 Offset

func Offset(n int) repository.Scope

Offset creates a scope that skips the specified number of records.

func OnlyDeleted

func OnlyDeleted() repository.Scope

OnlyDeleted creates a scope that returns only soft-deleted records.

func Order

func Order(order string) repository.Scope

Order creates a scope that adds an ORDER BY clause to the query.

func Select

func Select(cols ...string) repository.Scope

Select creates a scope that specifies which columns to select.

func Where

func Where(query any, args ...any) repository.Scope

Where creates a scope that adds a WHERE clause to the query. It accepts the same parameters as GORM's Where method.

func WhereEq

func WhereEq(m map[string]any) repository.Scope

WhereEq creates a scope that adds WHERE clauses for exact matches using a map of column names to values.

func WithDeleted

func WithDeleted() repository.Scope

WithDeleted creates a scope that includes soft-deleted records in the query. This is equivalent to GORM's Unscoped method.

Types

type GormRepository

type GormRepository[T any] struct {
	// contains filtered or unexported fields
}

GormRepository is a GORM-based implementation of the Repository interface. It wraps a GORM database instance and provides type-safe methods for CRUD operations, querying, and transaction handling.

func (*GormRepository[T]) BatchInsert

func (r *GormRepository[T]) BatchInsert(ctx context.Context, tx repository.Transaction, ents []*T, batchSize ...int) error

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 (*GormRepository[T]) Count

func (r *GormRepository[T]) Count(ctx context.Context, scopes ...repository.Scope) (int64, error)

Count returns the number of records that match the provided scopes.

func (*GormRepository[T]) Create

func (r *GormRepository[T]) Create(ctx context.Context, tx repository.Transaction, ent *T) error

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 (*GormRepository[T]) Delete

func (r *GormRepository[T]) Delete(ctx context.Context, tx repository.Transaction, scopes ...repository.Scope) error

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 (*GormRepository[T]) Exists

func (r *GormRepository[T]) Exists(ctx context.Context, scopes ...repository.Scope) (bool, error)

Exists checks whether any record matching the provided scopes exists. Returns true if at least one record exists, false otherwise.

func (*GormRepository[T]) FindForUpdate

func (r *GormRepository[T]) FindForUpdate(ctx context.Context, tx repository.Transaction, scopes ...repository.Scope) ([]T, error)

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 (*GormRepository[T]) First

func (r *GormRepository[T]) First(ctx context.Context, scopes ...repository.Scope) (T, error)

First retrieves the first record that matches the provided scopes. Returns ErrNotFound if no record is found.

func (*GormRepository[T]) FirstForUpdate

func (r *GormRepository[T]) FirstForUpdate(ctx context.Context, tx repository.Transaction, scopes ...repository.Scope) (T, error)

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 (*GormRepository[T]) List

func (r *GormRepository[T]) List(ctx context.Context, scopes ...repository.Scope) ([]T, error)

List retrieves all records that match the provided scopes. Consider using Limit and Order scopes to control the result set size and ordering.

func (*GormRepository[T]) Page

func (r *GormRepository[T]) Page(ctx context.Context, page, pageSize int, scopes ...repository.Scope) (repository.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 (*GormRepository[T]) Transact

func (r *GormRepository[T]) Transact(ctx context.Context, fn func(ctx context.Context, tx repository.Transaction) 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.

func (*GormRepository[T]) Update

func (r *GormRepository[T]) Update(ctx context.Context, tx repository.Transaction, ent *T) error

Update saves the entity to the database, updating all fields. If tx is provided, the operation is performed within that transaction. Otherwise, it uses the repository's default database connection.

type GormScope

type GormScope func(*gorm.DB) *gorm.DB

GormScope represents a function that can modify a GORM database query. It implements the repository.Scope interface for GORM-specific operations.

type InvalidPointer

type InvalidPointer *User

InvalidPointer is used for testing invalid types

type InvalidPrimitive

type InvalidPrimitive string

InvalidPrimitive is used for testing invalid types

type Product

type Product struct {
	ID          uint   `gorm:"primaryKey"`
	Name        string `gorm:"not null"`
	Price       int    `gorm:"not null"`
	Description string
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

Product represents a test product entity

type RepositoryTestSuite

type RepositoryTestSuite[T any] struct {
	// Factory function to create a new repository instance for testing
	NewRepo func() (repository.Repository[T], error)

	// Factory function to create a new entity for testing
	NewEntity func() *T

	// Function to modify an entity for update tests
	ModifyEntity func(*T)

	// Function to get the ID of an entity (for assertions)
	GetEntityID func(*T) any

	// Function to set up test database (if needed)
	SetupDB func(*testing.T)

	// Function to clean up test database (if needed)
	CleanupDB func(*testing.T)

	// Function to create a delete scope for the entity (implementation-specific)
	DeleteScope func(*T) repository.Scope
}

RepositoryTestSuite defines a comprehensive test suite that any Repository implementation must pass. This ensures all implementations conform to the same behavioral contract.

func ProductTestSuite

func ProductTestSuite(newRepo func() (repository.Repository[Product], error)) *RepositoryTestSuite[Product]

ProductTestSuite creates a test suite for Product entities

func UserTestSuite

func UserTestSuite(newRepo func() (repository.Repository[User], error)) *RepositoryTestSuite[User]

UserTestSuite creates a test suite for User entities

func (*RepositoryTestSuite[T]) RunAllTests

func (s *RepositoryTestSuite[T]) RunAllTests(t *testing.T)

RunAllTests runs the complete test suite for a repository implementation

func (*RepositoryTestSuite[T]) TestBatchOperations

func (s *RepositoryTestSuite[T]) TestBatchOperations(t *testing.T)

TestBatchOperations tests batch operations

func (*RepositoryTestSuite[T]) TestCRUDOperations

func (s *RepositoryTestSuite[T]) TestCRUDOperations(t *testing.T)

TestCRUDOperations tests basic CRUD operations

func (*RepositoryTestSuite[T]) TestErrorHandling

func (s *RepositoryTestSuite[T]) TestErrorHandling(t *testing.T)

TestErrorHandling tests error conditions

func (*RepositoryTestSuite[T]) TestLockingOperations

func (s *RepositoryTestSuite[T]) TestLockingOperations(t *testing.T)

TestLockingOperations tests row locking functionality

func (*RepositoryTestSuite[T]) TestPagination

func (s *RepositoryTestSuite[T]) TestPagination(t *testing.T)

TestPagination tests pagination functionality

func (*RepositoryTestSuite[T]) TestQueryOperations

func (s *RepositoryTestSuite[T]) TestQueryOperations(t *testing.T)

TestQueryOperations tests query operations

func (*RepositoryTestSuite[T]) TestTransactionOperations

func (s *RepositoryTestSuite[T]) TestTransactionOperations(t *testing.T)

TestTransactionOperations tests transaction functionality

type User

type User struct {
	ID        uint   `gorm:"primaryKey"`
	Name      string `gorm:"not null"`
	Email     string `gorm:"unique;not null"`
	Age       int    `gorm:"default:0"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
}

User represents a test user entity

Jump to

Keyboard shortcuts

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