Feat: Decide whether to do database migration based on version.lock

This commit is contained in:
HFO4
2019-11-09 19:04:48 +08:00
parent c5493fd1f1
commit e858cbe2cf
18 changed files with 127 additions and 26 deletions

View File

@@ -1,8 +1,8 @@
package model
import (
"Cloudreve/pkg/conf"
"Cloudreve/pkg/util"
"cloudreve/pkg/conf"
"cloudreve/pkg/util"
"fmt"
"github.com/jinzhu/gorm"
"time"
@@ -15,7 +15,6 @@ var DB *gorm.DB
// Database 在中间件中初始化mysql链接
func Init() {
//TODO 从配置文件中读取 包括DEBUG模式
util.Log().Info("初始化数据库连接\n")
var (
@@ -37,7 +36,11 @@ func Init() {
return conf.DatabaseConfig.TablePrefix + defaultTableName
}
db.LogMode(true)
// Debug 模式下,输出所有 SQL 日志
if conf.SystemConfig.Debug {
db.LogMode(true)
}
//db.SetLogger(util.Log())
if err != nil {
util.Log().Panic("连接数据库不成功", err)

View File

@@ -1,14 +1,31 @@
package model
import (
"Cloudreve/pkg/util"
"cloudreve/pkg/conf"
"cloudreve/pkg/util"
"github.com/jinzhu/gorm"
"github.com/mcuadros/go-version"
"io/ioutil"
)
//执行数据迁移
func migration() {
// 检查 version.lock 确认是否需要执行迁移
// Debug 模式下一定会执行迁移
if !conf.SystemConfig.Debug {
if util.Exists("version.lock") {
versionLock, _ := ioutil.ReadFile("version.lock")
if version.Compare(string(versionLock), conf.BackendVersion, "=") {
util.Log().Info("后端版本匹配,跳过数据库迁移")
return
}
}
}
util.Log().Info("开始进行数据库自动迁移...")
// 自动迁移模式
DB.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})
DB.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{}, &Setting{})
// 添加初始用户
_, err := GetUser(1)
@@ -29,4 +46,10 @@ func migration() {
}
}
// 迁移完毕后写入版本锁 version.lock
err = conf.WriteVersionLock()
if err != nil {
util.Log().Warning("无法写入版本控制锁 version.lock, ", err)
}
}

26
models/setting.go Normal file
View File

@@ -0,0 +1,26 @@
package model
import (
"github.com/jinzhu/gorm"
)
// Setting 系统设置模型
type Setting struct {
gorm.Model
Type string `gorm:"not null"`
Name string `gorm:"unique;not null;index:setting_key"`
Value string `gorm:"size:65535"`
}
// GetSettingByName 用 Name 获取设置值
func GetSettingByName(name string) (Setting, error) {
var setting Setting
// 优先尝试数据库中查找
result := DB.Where("name = ?", name).First(&setting)
if result.Error == nil {
return setting, nil
}
return setting, result.Error
}

View File

@@ -1,8 +1,8 @@
package model
import (
"Cloudreve/pkg/serializer"
"Cloudreve/pkg/util"
"cloudreve/pkg/serializer"
"cloudreve/pkg/util"
"crypto/sha1"
"encoding/hex"
"encoding/json"