Documentation ¶
Overview ¶
Package gormet provides a set of utility functions for performing common database operations using GORM.
Usage: To use this package, create a GORM repository for your entity, and embed the Repository struct into it. Then, you can call the various utility functions provided by this package to perform operations such as Get, GetById, Search, and SearchAll.
Example:
type UserRepository struct { gormet.Repository[User] } func NewUserRepository(db *gorm.DB) (*UserRepository, error) { repo, err := gormet.New[User](db) if err != nil { return nil, err } return &UserRepository{ Repository: repo, }, nil } // Now you can use the utility functions like Get, GetById, Search, and SearchAll on UserRepository. import ( "github.com/example/gormet" "gorm.io/gorm" ) type User struct { gorm.Model Username string Email string } userRepo, err := NewUserRepository(db) if err != nil { // Handle error } // Retrieve a user by ID userByID, err := userRepo.GetById(1) if err != nil { // Handle error } // Search for users based on a filter users, err := userRepo.Search(1, "username = ?", "john_doe") if err != nil { // Handle error }
Index ¶
- type Pagination
- type Repository
- func (r *Repository[T]) Create(entity *T) error
- func (r *Repository[T]) Delete(entity *T) error
- func (r *Repository[T]) DeleteById(id interface{}) error
- func (r *Repository[T]) Get(entity T) (*T, error)
- func (r *Repository[T]) GetById(id interface{}) (*T, error)
- func (r *Repository[T]) GetLatest() (*T, error)
- func (r *Repository[T]) Search(page uint, query interface{}, args ...interface{}) (Pagination[T], error)
- func (r *Repository[T]) SearchAll(query interface{}, args ...interface{}) ([]T, error)
- func (r *Repository[T]) Update(entity *T) error
- type Response
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Pagination ¶
type Pagination[T any] struct { Response Response[T] `json:"response"` // contains filtered or unexported fields }
Pagination contains the response with actual content and additional data for paginated searches.
type Repository ¶
type Repository[T any] struct { PageSize uint // Define if the size of page // contains filtered or unexported fields }
Repository is a generic repository type that provides CRUD operations for a given model that is represented by a GORM model.
func New ¶
func New[T any](db *gorm.DB) (*Repository[T], error)
New creates and returns a new instance of Repository for a specific model type T, with the provided database connection and optional configuration settings. It automatically determines the primary key field for the model type T.
Usage: repo, err := New[YourModelType](db, nil)
if err != nil { // Handle error }
Parameters:
- db: A *gorm.DB instance representing the database connection.
Returns: - A pointer to a newly created Repository for type T if successful. - An error if there is a failure in determining the primary key or other initializations.
func (*Repository[T]) Create ¶
func (r *Repository[T]) Create(entity *T) error
Create inserts a new entity of type T into the database.
This method ensures the entity is not nil before attempting to create it in the database. It leverages GORM's Create method, which persists the entity's data into the corresponding table in the database. If the operation is successful, it returns nil, indicating no error occurred. If the operation fails, it returns an error, which could be due to constraints like unique violations, missing required fields, or database connectivity issues.
Usage: err := repo.Create(&entity)
if err != nil { // Handle error }
Parameters:
- entity: A pointer to an instance of type T that represents the entity to be created in the database. The entity should be a valid non-nil pointer to a struct that GORM can map to a database table.
Returns: - nil if the entity is successfully created in the database. - An error if the entity is nil or if GORM encounters any issues while creating the record.
func (*Repository[T]) Delete ¶
func (r *Repository[T]) Delete(entity *T) error
Delete removes an entity from the database.
This method takes an entity as an argument, ensures it is not nil, and then uses GORM's Delete method to delete the corresponding record from the database. If the operation is successful, it returns nil. If the operation fails, an error is returned, which could be due to database connectivity issues or other constraints.
Usage: err := repo.Delete(&entity)
if err != nil { // Handle error }
Parameters:
- entity: A pointer to an instance of type T that represents the entity to be deleted from the database. It should not be nil.
Returns: - nil if the entity is successfully deleted from the database. - An error if the entity is nil or if GORM encounters any issues while deleting the record.
func (*Repository[T]) DeleteById ¶
func (r *Repository[T]) DeleteById(id interface{}) error
DeleteById removes an entity from the database using its ID.
This method takes an ID as an argument, ensures it is not nil, and then uses GORM's Delete method to delete the corresponding record from the database. The repository's primary key name is used in the query condition. If the operation is successful, it returns nil. If the operation fails, an error is returned, which could be due to database connectivity issues or other constraints.
Usage: err := repo.DeleteById(id)
if err != nil { // Handle error }
Parameters:
- id: An interface{} representing the ID of the entity to be deleted from the database. It should not be nil.
Returns: - nil if the entity is successfully deleted from the database. - An error if the ID is nil or if GORM encounters any issues while deleting the record.
func (*Repository[T]) Get ¶
func (r *Repository[T]) Get(entity T) (*T, error)
Get retrieves a single entity from the database based on the provided filter criteria. It takes a pointer to the repository, an entity object as a filter, and returns a pointer to the retrieved entity and an error, if any.
Example:
userRepo, err := NewUserRepository(db) if err != nil { // Handle error } // Create a sample user entity for filtering filterUser := User{ID: 1} // Retrieve the user entity from the database based on the filter retrievedUser, err := userRepo.Get(filterUser) if err != nil { // Handle error }
Parameters: - entity: An object of the entity type with the filter criteria.
Returns: - A pointer to the retrieved entity. - An error if the retrieval operation encounters any issues.
func (*Repository[T]) GetById ¶
func (r *Repository[T]) GetById(id interface{}) (*T, error)
GetById retrieves a single entity from the database based on its unique identifier (id). It takes a pointer to the repository and the id of the entity, and returns a pointer to the retrieved entity and an error, if any.
Example:
userRepo, err := NewUserRepository(db) if err != nil { // Handle error } // Provide the unique identifier for the user to be retrieved userId := 1 // Retrieve the user entity from the database based on the unique identifier retrievedUser, err := userRepo.GetById(userId) if err != nil { // Handle error }
Parameters: - id: The unique identifier of the entity.
Returns: - A pointer to the retrieved entity. - An error if the retrieval operation encounters any issues, including if the provided id is nil.
func (*Repository[T]) GetLatest ¶
func (r *Repository[T]) GetLatest() (*T, error)
GetLatest retrieves the latest entity from the database without any filter criteria. It takes a pointer to the repository and returns a pointer to the retrieved entity and an error, if any.
Example:
userRepo, err := NewUserRepository(db) if err != nil { // Handle error } // Retrieve the latest user entity from the database latestUser, err := userRepo.GetLatest() if err != nil { // Handle error }
Returns: - A pointer to the retrieved entity. - An error if the retrieval operation encounters any issues.
func (*Repository[T]) Search ¶
func (r *Repository[T]) Search(page uint, query interface{}, args ...interface{}) (Pagination[T], error)
Search performs a paginated search for entities in the database based on given criteria.
This method takes a GORM query condition, performs a paginated search using GORM's Find method, and returns the paginated results. The paginated results include the entities found and additional information such as total count and pagination details.
Usage: query := "your_column = ?" args := []interface{}{"your_value"} pagination, err := repo.Search(page, query, args...)
if err != nil { // Handle error }
// Use pagination for further processing
Parameters: - page: The page number for pagination (starting from 1). - query: GORM query condition. - args: Arguments for the query condition.
Returns: - A structure containing the paginated search results, including entities, total count, and pagination details. - An error if the search operation encounters any issues.
func (*Repository[T]) SearchAll ¶
func (r *Repository[T]) SearchAll(query interface{}, args ...interface{}) ([]T, error)
SearchAll performs a paginated search for all entities in the database based on given criteria.
This method takes a GORM query condition, performs a paginated search using GORM's Find method, and returns the paginated results. The paginated results include all entities found and additional information such as total count and pagination details.
Usage: query := "your_column = ?" args := []interface{}{"your_value"} pagination, err := repo.SearchAll(query, args...)
if err != nil { // Handle error }
// Use pagination for further processing
Parameters: - query: GORM query condition. - args: Arguments for the query condition.
Returns: - A structure containing the paginated search results, including entities, total count, and pagination details. - An error if the search operation encounters any issues.
func (*Repository[T]) Update ¶
func (r *Repository[T]) Update(entity *T) error
Update modifies an existing entity of type T in the database.
This method ensures the entity is not nil before attempting to update it in the database. It uses GORM's Save method, which updates the entity's data in the corresponding table in the database. If the operation is successful, it returns nil, indicating no error occurred. If the operation fails, it returns an error, which could be due to constraints like unique violations, missing required fields, or database connectivity issues.
Usage: err := repo.Update(&entity)
if err != nil { // Handle error }
Parameters:
- entity: A pointer to an instance of type T that represents the entity to be updated in the database. The entity should be a valid non-nil pointer to a struct that GORM can map to a database table.
Returns: - nil if the entity is successfully updated in the database. - An error if the entity is nil or if GORM encounters any issues while updating the record.
type Response ¶
type Response[T any] struct { Entities []T `json:"entities"` TotalCount int64 `json:"totalCount"` Page uint `json:"page"` PageSize uint `json:"pageSize"` TotalPages int64 `json:"totalPages"` HasNextPage bool `json:"hasNextPage"` HasPrevPage bool `json:"hasPrevPage"` }
Response represents the paginated search results including entities, total count, and pagination details.