2022-08-16 23:30:23 +08:00
|
|
|
package repo
|
|
|
|
|
2022-10-11 16:27:58 +08:00
|
|
|
import (
|
|
|
|
"context"
|
2022-11-02 15:19:14 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/constant"
|
2022-10-17 16:32:31 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/global"
|
2022-10-11 16:27:58 +08:00
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
2022-08-16 23:30:23 +08:00
|
|
|
|
|
|
|
type DBOption func(*gorm.DB) *gorm.DB
|
|
|
|
|
|
|
|
type ICommonRepo interface {
|
|
|
|
WithByID(id uint) DBOption
|
|
|
|
WithByName(name string) DBOption
|
|
|
|
WithOrderBy(orderStr string) DBOption
|
|
|
|
WithLikeName(name string) DBOption
|
|
|
|
WithIdsIn(ids []uint) DBOption
|
|
|
|
}
|
|
|
|
|
|
|
|
type CommonRepo struct{}
|
|
|
|
|
|
|
|
func (c *CommonRepo) WithByID(id uint) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
return g.Where("id = ?", id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *CommonRepo) WithByName(name string) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
return g.Where("name = ?", name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-19 19:42:06 +08:00
|
|
|
func (c *CommonRepo) WithByType(name string) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
return g.Where("type = ?", name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-23 17:21:27 +08:00
|
|
|
func (c *CommonRepo) WithByStatus(status string) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
if len(status) == 0 {
|
|
|
|
return g
|
|
|
|
}
|
|
|
|
return g.Where("status = ?", status)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-16 23:30:23 +08:00
|
|
|
func (c *CommonRepo) WithLikeName(name string) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
return g.Where("name like ?", "%"+name+"%")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *CommonRepo) WithOrderBy(orderStr string) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
return g.Order(orderStr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *CommonRepo) WithIdsIn(ids []uint) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
return g.Where("id in (?)", ids)
|
|
|
|
}
|
|
|
|
}
|
2022-10-11 16:27:58 +08:00
|
|
|
|
2022-10-12 10:54:09 +08:00
|
|
|
func (c *CommonRepo) WithIdsNotIn(ids []uint) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
return g.Where("id not in (?)", ids)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-11 16:27:58 +08:00
|
|
|
func getTx(ctx context.Context, opts ...DBOption) *gorm.DB {
|
2022-11-02 15:19:14 +08:00
|
|
|
if ctx == nil || ctx.Value(constant.DB) == nil {
|
2022-10-13 16:46:38 +08:00
|
|
|
return getDb()
|
|
|
|
}
|
2022-11-02 15:19:14 +08:00
|
|
|
tx := ctx.Value(constant.DB).(*gorm.DB)
|
2022-10-11 16:27:58 +08:00
|
|
|
for _, opt := range opts {
|
|
|
|
tx = opt(tx)
|
|
|
|
}
|
|
|
|
return tx
|
|
|
|
}
|
|
|
|
|
|
|
|
func getDb(opts ...DBOption) *gorm.DB {
|
|
|
|
db := global.DB
|
|
|
|
for _, opt := range opts {
|
|
|
|
db = opt(db)
|
|
|
|
}
|
|
|
|
return db
|
|
|
|
}
|