From 0fb31f4523746c777fc463e34d71f3d060f4d515 Mon Sep 17 00:00:00 2001 From: HFO4 <912394456@qq.com> Date: Sun, 24 Apr 2022 15:16:25 +0800 Subject: [PATCH] fix: deadlock while creating default user in SQLite --- assets | 2 +- models/file.go | 8 ++++++-- models/setting.go | 20 +++++++++++++++----- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/assets b/assets index ac3af60..0deacc2 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit ac3af6097f5438d9d24afc22a9a4aacd212deb69 +Subproject commit 0deacc2d4dea2087bf065dc2946fde1670a7fd03 diff --git a/models/file.go b/models/file.go index d377641..3a125fa 100644 --- a/models/file.go +++ b/models/file.go @@ -102,12 +102,16 @@ func (folder *Folder) GetChildFiles() ([]File, error) { // GetFilesByIDs 根据文件ID批量获取文件, // UID为0表示忽略用户,只根据文件ID检索 func GetFilesByIDs(ids []uint, uid uint) ([]File, error) { + return GetFilesByIDsFromTX(DB, ids, uid) +} + +func GetFilesByIDsFromTX(tx *gorm.DB, ids []uint, uid uint) ([]File, error) { var files []File var result *gorm.DB if uid == 0 { - result = DB.Where("id in (?)", ids).Find(&files) + result = tx.Where("id in (?)", ids).Find(&files) } else { - result = DB.Where("id in (?) AND user_id = ?", ids, uid).Find(&files) + result = tx.Where("id in (?) AND user_id = ?", ids, uid).Find(&files) } return files, result.Error } diff --git a/models/setting.go b/models/setting.go index 643ca84..0bbcf68 100644 --- a/models/setting.go +++ b/models/setting.go @@ -23,6 +23,11 @@ func IsTrueVal(val string) bool { // GetSettingByName 用 Name 获取设置值 func GetSettingByName(name string) string { + return GetSettingByNameFromTx(DB, name) +} + +// GetSettingByNameFromTx 用 Name 获取设置值,使用事务 +func GetSettingByNameFromTx(tx *gorm.DB, name string) string { var setting Setting // 优先从缓存中查找 @@ -32,14 +37,19 @@ func GetSettingByName(name string) string { } // 尝试数据库中查找 - if DB != nil { - result := DB.Where("name = ?", name).First(&setting) - if result.Error == nil { - _ = cache.Set(cacheKey, setting.Value, -1) - return setting.Value + if tx == nil { + tx = DB + if tx == nil { + return "" } } + result := tx.Where("name = ?", name).First(&setting) + if result.Error == nil { + _ = cache.Set(cacheKey, setting.Value, -1) + return setting.Value + } + return "" }