Skip to content

Commit

Permalink
refactor(database): 切换后端数据库操作库至gorm (#1060)
Browse files Browse the repository at this point in the history
Co-authored-by: JustAnotherID <[email protected]>
  • Loading branch information
PaienNate and JustAnotherID authored Nov 7, 2024
1 parent 202aa9e commit cd7e329
Show file tree
Hide file tree
Showing 35 changed files with 1,493 additions and 1,057 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,4 @@ _help_cache

.vscode/
!.vscode/settings.json
sealdice-lock.lock
18 changes: 15 additions & 3 deletions api/api_bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,11 @@ func forceStop(c echo.Context) error {
dbData := d.DBData
if dbData != nil {
d.DBData = nil
_ = dbData.Close()
db, err := dbData.DB()
if err != nil {
return
}
_ = db.Close()
}
})()

Expand All @@ -201,7 +205,11 @@ func forceStop(c echo.Context) error {
dbLogs := d.DBLogs
if dbLogs != nil {
d.DBLogs = nil
_ = dbLogs.Close()
db, err := dbLogs.DB()
if err != nil {
return
}
_ = db.Close()
}
})()

Expand All @@ -213,7 +221,11 @@ func forceStop(c echo.Context) error {
if cm != nil && cm.DB != nil {
dbCensor := cm.DB
cm.DB = nil
_ = dbCensor.Close()
db, err := dbCensor.DB()
if err != nil {
return
}
_ = db.Close()
}
})()
}
Expand Down
9 changes: 8 additions & 1 deletion api/censor.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,14 @@ func censorStop(c echo.Context) error {

(&myDice.Config).EnableCensor = false
myDice.MarkModified()
_ = myDice.CensorManager.DB.Close()
db, err2 := myDice.CensorManager.DB.DB()
if err2 != nil {
return Error(&c, "关闭拦截引擎失败", Response{})
}
err = db.Close()
if err != nil {
return err
}
myDice.CensorManager = nil

return Success(&c, Response{})
Expand Down
2 changes: 1 addition & 1 deletion dice/builtin_commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -1917,7 +1917,7 @@ func (d *Dice) registerCoreCommands() {
setCurPlayerName(b)
}
attrs.LastModifiedTime = time.Now().Unix()
attrs.SaveToDB(am.db, nil) // 直接保存
attrs.SaveToDB(am.db) // 直接保存
ReplyToSender(ctx, msg, "操作完成")
} else {
ReplyToSender(ctx, msg, "此角色名已存在")
Expand Down
15 changes: 8 additions & 7 deletions dice/dice.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ import (
"github.com/dop251/goja_nodejs/eventloop"
"github.com/dop251/goja_nodejs/require"
"github.com/go-creed/sat"
"github.com/jmoiron/sqlx"
wr "github.com/mroth/weightedrand"
"github.com/robfig/cron/v3"
ds "github.com/sealdice/dicescript"
"github.com/tidwall/buntdb"
rand2 "golang.org/x/exp/rand"
"golang.org/x/exp/slices"
"gorm.io/gorm"

"sealdice-core/dice/logger"
"sealdice-core/dice/model"
Expand Down Expand Up @@ -133,8 +133,8 @@ type Dice struct {
LastUpdatedTime int64 `yaml:"-"`
TextMap map[string]*wr.Chooser `yaml:"-"`
BaseConfig BaseConfig `yaml:"-"`
DBData *sqlx.DB `yaml:"-"` // 数据库对象
DBLogs *sqlx.DB `yaml:"-"` // 数据库对象
DBData *gorm.DB `yaml:"-"` // 数据库对象
DBLogs *gorm.DB `yaml:"-"` // 数据库对象
Logger *log.Helper `yaml:"-"` // 日志
LogWriter *log.WriterX `yaml:"-"` // 用于api的log对象
IsDeckLoading bool `yaml:"-"` // 正在加载中
Expand All @@ -160,10 +160,11 @@ type Dice struct {
AliveNoticeEntry cron.EntryID `yaml:"-" json:"-"`
JsPrinter *PrinterFunc `yaml:"-" json:"-"`
JsRequire *require.RequireModule `yaml:"-" json:"-"`
JsLoop *eventloop.EventLoop `yaml:"-" json:"-"`
JsScriptList []*JsScriptInfo `yaml:"-" json:"-"`
JsScriptCron *cron.Cron `yaml:"-" json:"-"`
JsScriptCronLock *sync.Mutex `yaml:"-" json:"-"`

JsLoop *eventloop.EventLoop `yaml:"-" json:"-"`
JsScriptList []*JsScriptInfo `yaml:"-" json:"-"`
JsScriptCron *cron.Cron `yaml:"-" json:"-"`
JsScriptCronLock *sync.Mutex `yaml:"-" json:"-"`
// 重载使用的互斥锁
JsReloadLock sync.Mutex `yaml:"-" json:"-"`
// 内置脚本摘要表,用于判断内置脚本是否有更新
Expand Down
24 changes: 9 additions & 15 deletions dice/dice_attrs_manager.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
package dice

import (
"database/sql"
"errors"
"fmt"
"time"

"github.com/jmoiron/sqlx"
ds "github.com/sealdice/dicescript"
"gorm.io/gorm"

"sealdice-core/dice/model"
log "sealdice-core/utils/kratos"
)

type AttrsManager struct {
db *sqlx.DB
db *gorm.DB
logger *log.Helper
m SyncMap[string, *AttributesItem]
}
Expand Down Expand Up @@ -169,24 +168,18 @@ func (am *AttrsManager) CheckForSave() (int, int) {
return 0, 0
}

tx, err := db.Begin()
if err != nil {
if am.logger != nil {
am.logger.Errorf("定期写入用户数据出错(创建事务): %v", err)
}
return 0, 0
}
tx := db.Begin()

am.m.Range(func(key string, value *AttributesItem) bool {
if !value.IsSaved {
saved += 1
value.SaveToDB(db, tx)
value.SaveToDB(tx)
}
times += 1
return true
})

err = tx.Commit()
err := tx.Commit().Error
if err != nil {
if am.logger != nil {
am.logger.Errorf("定期写入用户数据出错(提交事务): %v", err)
Expand All @@ -210,7 +203,8 @@ func (am *AttrsManager) CheckAndFreeUnused() {
am.m.Range(func(key string, value *AttributesItem) bool {
if value.LastUsedTime-currentTime > 60*10 {
prepareToFree[key] = 1
value.SaveToDB(am.db, nil)
// 直接保存
value.SaveToDB(am.db)
}
return true
})
Expand Down Expand Up @@ -279,13 +273,13 @@ type AttributesItem struct {
SheetType string
}

func (i *AttributesItem) SaveToDB(db *sqlx.DB, tx *sql.Tx) {
func (i *AttributesItem) SaveToDB(db *gorm.DB) {
// 使用事务写入
rawData, err := ds.NewDictVal(i.valueMap).V().ToJSON()
if err != nil {
return
}
err = model.AttrsPutById(db, tx, i.ID, rawData, i.Name, i.SheetType)
err = model.AttrsPutById(db, i.ID, rawData, i.Name, i.SheetType)
if err != nil {
log.Error("保存数据失败", err.Error())
return
Expand Down
4 changes: 2 additions & 2 deletions dice/dice_censor.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"sort"
"strings"

"github.com/jmoiron/sqlx"
"gorm.io/gorm"

"sealdice-core/dice/censor"
"sealdice-core/dice/model"
Expand Down Expand Up @@ -54,7 +54,7 @@ type CensorManager struct {
IsLoading bool
Parent *Dice
Censor *censor.Censor
DB *sqlx.DB
DB *gorm.DB
SensitiveWordsFiles map[string]*censor.WordFile
}

Expand Down
5 changes: 3 additions & 2 deletions dice/im_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"strings"
"time"

"gorm.io/gorm"

"sealdice-core/dice/model"
"sealdice-core/message"
log "sealdice-core/utils/kratos"
Expand All @@ -20,7 +22,6 @@ import (
rand2 "golang.org/x/exp/rand"

"github.com/dop251/goja"
"github.com/jmoiron/sqlx"
"golang.org/x/time/rate"
"gopkg.in/yaml.v3"
)
Expand Down Expand Up @@ -192,7 +193,7 @@ func (group *GroupInfo) IsActive(ctx *MsgContext) bool {
return false
}

func (group *GroupInfo) PlayerGet(db *sqlx.DB, id string) *GroupPlayerInfo {
func (group *GroupInfo) PlayerGet(db *gorm.DB, id string) *GroupPlayerInfo {
if group.Players == nil {
group.Players = new(SyncMap[string, *GroupPlayerInfo])
}
Expand Down
2 changes: 2 additions & 0 deletions dice/model/attr.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"github.com/jmoiron/sqlx"
)

// 废弃代码先不改

func attrGetAllBase(db *sqlx.DB, bucket string, key string) []byte {
var buf []byte

Expand Down
Loading

0 comments on commit cd7e329

Please sign in to comment.