From dc2b113d967c0f2abce1053af24796d8db12c2cc Mon Sep 17 00:00:00 2001 From: ochom Date: Thu, 29 Feb 2024 10:58:58 +0300 Subject: [PATCH] adjust query implementations --- sql/common.go | 50 +++++++------------------------------------------- 1 file changed, 7 insertions(+), 43 deletions(-) diff --git a/sql/common.go b/sql/common.go index 94a5eef..fcd4789 100644 --- a/sql/common.go +++ b/sql/common.go @@ -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 } @@ -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