Files
EdgeAPI/internal/db/models/sys_setting_dao.go
2020-10-02 17:22:32 +08:00

87 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package models
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
)
type SysSettingDAO dbs.DAO
type SettingCode = string
const (
SettingCodeGlobalConfig SettingCode = "globalConfig"
)
func NewSysSettingDAO() *SysSettingDAO {
return dbs.NewDAO(&SysSettingDAO{
DAOObject: dbs.DAOObject{
DB: Tea.Env,
Table: "edgeSysSettings",
Model: new(SysSetting),
PkName: "id",
},
}).(*SysSettingDAO)
}
var SharedSysSettingDAO = NewSysSettingDAO()
// 设置配置
func (this *SysSettingDAO) UpdateSetting(codeFormat string, valueJSON []byte, codeFormatArgs ...interface{}) error {
if len(codeFormatArgs) > 0 {
codeFormat = fmt.Sprintf(codeFormat, codeFormatArgs...)
}
countRetries := 3
var lastErr error
for i := 0; i < countRetries; i++ {
settingId, err := this.Query().
Attr("code", codeFormat).
ResultPk().
FindInt64Col(0)
if err != nil {
return err
}
if settingId == 0 {
// 新建
op := NewSysSettingOperator()
op.Code = codeFormat
op.Value = valueJSON
_, err = this.Save(op)
if err != nil {
lastErr = err
// 因为错误的原因可能是因为code冲突所以这里我们继续执行
continue
}
return nil
}
// 修改
op := NewSysSettingOperator()
op.Id = settingId
op.Value = valueJSON
_, err = this.Save(op)
if err != nil {
return err
}
}
return lastErr
}
// 读取配置
func (this *SysSettingDAO) ReadSetting(code string, args ...interface{}) (valueJSON []byte, err error) {
if len(args) > 0 {
code = fmt.Sprintf(code, args...)
}
col, err := this.Query().
Attr("code", code).
Result("value").
FindStringCol("")
return []byte(col), err
}