Files
OpenList/bootstrap/model.go

45 lines
1.1 KiB
Go
Raw Normal View History

2021-03-04 23:50:51 +08:00
package bootstrap
import (
"github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/server/models"
"github.com/Xhofe/alist/utils"
log "github.com/sirupsen/logrus"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
2021-03-08 20:26:02 +08:00
"strings"
2021-03-04 23:50:51 +08:00
)
func InitModel() bool {
log.Infof("初始化数据库...")
switch conf.Conf.Database.Type {
2021-03-05 21:07:45 +08:00
case "sqlite3":
{
2021-03-08 20:26:02 +08:00
if !(strings.HasSuffix(conf.Conf.Database.DBFile, ".db") && len(conf.Conf.Database.DBFile) > 3) {
log.Errorf("db名称不正确.")
return false
}
2021-03-05 21:07:45 +08:00
needMigrate := !utils.Exists(conf.Conf.Database.DBFile)
db, err := gorm.Open(sqlite.Open(conf.Conf.Database.DBFile), &gorm.Config{})
if err != nil {
log.Errorf("连接数据库出现错误:%s", err.Error())
2021-03-04 23:50:51 +08:00
return false
}
2021-03-05 21:07:45 +08:00
conf.DB = db
if needMigrate {
log.Infof("迁移数据库...")
err = conf.DB.AutoMigrate(&models.File{})
if err != nil {
log.Errorf("数据库迁移失败:%s", err.Error())
return false
}
2021-03-16 21:25:16 +08:00
models.BuildTreeAll()
2021-03-05 21:07:45 +08:00
}
return true
2021-03-04 23:50:51 +08:00
}
default:
log.Errorf("不支持的数据库类型:%s", conf.Conf.Database.Type)
return false
}
}