Skip to content

Commit

Permalink
adjust query implementations
Browse files Browse the repository at this point in the history
  • Loading branch information
ochom committed Feb 29, 2024
1 parent 971f08d commit dc2b113
Showing 1 changed file with 7 additions and 43 deletions.
50 changes: 7 additions & 43 deletions sql/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,31 +18,9 @@ func Delete[T any](query *T) error {
}

// FindOne ...
func FindOne[T any](query *T) (*T, error) {
func FindOne[T any](query *T, scopes ...func(*gorm.DB) *gorm.DB) (*T, error) {
var data T
err := conn.First(&data, query).Error
if err != nil {
return nil, err
}

return &data, nil
}

// ScopeOne ...
func ScopeOne[T any](scopes ...func(*gorm.DB) *gorm.DB) (*T, error) {
var data T
err := conn.Scopes(scopes...).First(&data).Error
if err != nil {
return nil, err
}

return &data, nil
}

// QueryOne ...
func QueryOne[T any](query interface{}) (*T, error) {
var data T
err := conn.First(&data, query).Error
err := conn.Scopes(scopes...).First(&data, query).Error
if err != nil {
return nil, err
}
Expand All @@ -51,36 +29,22 @@ func QueryOne[T any](query interface{}) (*T, error) {
}

// FindAll ...
func FindAll[T any](query *T) ([]*T, error) {
data := []*T{}
err := conn.Find(&data, query).Error
return data, err
}

// ScopeAll ...
func ScopeAll[T any](scopes ...func(*gorm.DB) *gorm.DB) ([]*T, error) {
data := []*T{}
err := conn.Scopes(scopes...).Find(&data).Error
return data, err
}

// QueryAll ...
func QueryAll[T any](query interface{}) ([]*T, error) {
func FindAll[T any](query *T, scopes ...func(*gorm.DB) *gorm.DB) ([]*T, error) {
data := []*T{}
err := conn.Find(&data, query).Error
err := conn.Scopes(scopes...).Find(&data, query).Error
return data, err
}

// FindWithLimit ...
func FindWithLimit[T any](query *T, page, limit int) ([]*T, error) {
func FindWithLimit[T any](query *T, page, limit int, scopes ...func(*gorm.DB) *gorm.DB) ([]*T, error) {
data := []*T{}

err := conn.Offset((page-1)*limit).Limit(limit).Find(&data, query).Error
err := conn.Scopes(scopes...).Offset((page-1)*limit).Limit(limit).Find(&data, query).Error
return data, err
}

// Count ...
func Count[T any](query *T) (int64, error) {
func Count[T any](query *T, scopes ...func(*gorm.DB) *gorm.DB) (int64, error) {
var count int64
var model T
err := conn.Model(&model).Where(query).Count(&count).Error
Expand Down

0 comments on commit dc2b113

Please sign in to comment.