67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
package repository
|
|
|
|
import (
|
|
"Blog/internal/client"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type BaseRep[T any] struct {
|
|
*client.DB
|
|
TableName string
|
|
}
|
|
|
|
func (rep *BaseRep[T]) WGorm(txFunc func(tx *gorm.DB) error) error {
|
|
rep.DB.Mutex.Lock()
|
|
err := rep.DB.Transaction(txFunc)
|
|
rep.DB.Mutex.Unlock()
|
|
return err
|
|
}
|
|
|
|
func (repository *BaseRep[T]) GetById(id string) (ret *T) {
|
|
ret = new(T)
|
|
sql := repository.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
|
return tx.Table(repository.TableName).First(ret, "id = ?", id)
|
|
})
|
|
logrus.Debug("执行的SQL:", sql)
|
|
err := repository.Table(repository.TableName).First(ret, "id = ?", id).Error
|
|
if err != nil {
|
|
logrus.Error(err)
|
|
return nil
|
|
}
|
|
|
|
return ret
|
|
}
|
|
|
|
func (repository *BaseRep[T]) FindList(order interface{}, conds ...interface{}) (ret []T) {
|
|
sql := repository.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
|
return tx.Table(repository.TableName).Find(&ret, conds...)
|
|
})
|
|
logrus.Debug("执行的SQL:", sql)
|
|
db := repository.Table(repository.TableName)
|
|
if order != nil {
|
|
db = db.Order(order)
|
|
}
|
|
err := db.Find(&ret, conds...).Error
|
|
if err != nil {
|
|
logrus.Info(err)
|
|
return nil
|
|
}
|
|
return ret
|
|
}
|
|
|
|
func (repository *BaseRep[T]) FindOne(conds ...interface{}) (ret *T) {
|
|
ret = new(T)
|
|
sql := repository.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
|
return tx.Table(repository.TableName).First(ret, conds...)
|
|
})
|
|
logrus.Debug("执行的SQL:", sql)
|
|
err := repository.Table(repository.TableName).First(ret, conds...).Error
|
|
if err != nil {
|
|
logrus.Info(err)
|
|
return nil
|
|
}
|
|
return ret
|
|
}
|