1Panel/backend/app/repo/databse_mysql.go

84 lines
2.3 KiB
Go
Raw Normal View History

2022-10-20 18:45:47 +08:00
package repo
import (
2022-11-18 17:50:52 +08:00
"context"
2022-10-25 18:34:33 +08:00
2022-10-20 18:45:47 +08:00
"github.com/1Panel-dev/1Panel/backend/app/model"
"github.com/1Panel-dev/1Panel/backend/global"
2022-10-25 18:34:33 +08:00
"gorm.io/gorm"
2022-10-20 18:45:47 +08:00
)
type MysqlRepo struct{}
type IMysqlRepo interface {
Get(opts ...DBOption) (model.DatabaseMysql, error)
WithByMysqlName(mysqlName string) DBOption
List(opts ...DBOption) ([]model.DatabaseMysql, error)
2022-10-20 18:45:47 +08:00
Page(limit, offset int, opts ...DBOption) (int64, []model.DatabaseMysql, error)
2022-11-18 17:50:52 +08:00
Create(ctx context.Context, mysql *model.DatabaseMysql) error
Delete(ctx context.Context, opts ...DBOption) error
Update(id uint, vars map[string]interface{}) error
UpdateDatabaseInfo(id uint, vars map[string]interface{}) error
2022-10-20 18:45:47 +08:00
}
func NewIMysqlRepo() IMysqlRepo {
return &MysqlRepo{}
}
func (u *MysqlRepo) Get(opts ...DBOption) (model.DatabaseMysql, error) {
var mysql model.DatabaseMysql
db := global.DB
for _, opt := range opts {
db = opt(db)
}
err := db.First(&mysql).Error
return mysql, err
}
func (u *MysqlRepo) List(opts ...DBOption) ([]model.DatabaseMysql, error) {
var users []model.DatabaseMysql
db := global.DB.Model(&model.DatabaseMysql{})
for _, opt := range opts {
db = opt(db)
}
err := db.Find(&users).Error
return users, err
}
2022-10-20 18:45:47 +08:00
func (u *MysqlRepo) Page(page, size int, opts ...DBOption) (int64, []model.DatabaseMysql, error) {
var users []model.DatabaseMysql
db := global.DB.Model(&model.DatabaseMysql{})
for _, opt := range opts {
db = opt(db)
}
count := int64(0)
db = db.Count(&count)
err := db.Limit(size).Offset(size * (page - 1)).Find(&users).Error
return count, users, err
}
2022-11-18 17:50:52 +08:00
func (u *MysqlRepo) Create(ctx context.Context, mysql *model.DatabaseMysql) error {
return getTx(ctx).Create(mysql).Error
2022-10-20 18:45:47 +08:00
}
2022-11-18 17:50:52 +08:00
func (u *MysqlRepo) Delete(ctx context.Context, opts ...DBOption) error {
return getTx(ctx, opts...).Delete(&model.DatabaseMysql{}).Error
2022-10-20 18:45:47 +08:00
}
func (u *MysqlRepo) Update(id uint, vars map[string]interface{}) error {
return global.DB.Model(&model.DatabaseMysql{}).Where("id = ?", id).Updates(vars).Error
}
2022-10-25 18:34:33 +08:00
func (u *MysqlRepo) UpdateDatabaseInfo(id uint, vars map[string]interface{}) error {
2022-10-25 18:34:33 +08:00
if err := global.DB.Model(&model.AppInstall{}).Where("id = ?", id).Updates(vars).Error; err != nil {
return err
}
return nil
}
2022-11-18 17:50:52 +08:00
func (u *MysqlRepo) WithByMysqlName(mysqlName string) DBOption {
2022-10-25 18:34:33 +08:00
return func(g *gorm.DB) *gorm.DB {
return g.Where("mysql_name = ?", mysqlName)
2022-10-25 18:34:33 +08:00
}
}