fix(db_driver): fix the panic when sqlite3 is used in the conf (#551)

* fix(db_driver): fix the panic when sqlite3 is used in the conf

fix the panic when sqlite3 is used in the conf

ref cloudreve/Cloudreve#550

Signed-off-by: mritd <mritd@linux.com>

* fix(nullpointer): fix possible null pointer error

fix possible null pointer error

Signed-off-by: mritd <mritd@linux.com>
pull/560/head
mritd 4 years ago committed by GitHub
parent f478c38307
commit 7df09537e0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -2,11 +2,12 @@ package model
import ( import (
"fmt" "fmt"
"time"
"github.com/HFO4/cloudreve/pkg/conf" "github.com/HFO4/cloudreve/pkg/conf"
"github.com/HFO4/cloudreve/pkg/util" "github.com/HFO4/cloudreve/pkg/util"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"time"
_ "github.com/jinzhu/gorm/dialects/mysql" _ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/sqlite" _ "github.com/jinzhu/gorm/dialects/sqlite"
@ -28,19 +29,30 @@ func Init() {
// 测试模式下,使用内存数据库 // 测试模式下,使用内存数据库
db, err = gorm.Open("sqlite3", ":memory:") db, err = gorm.Open("sqlite3", ":memory:")
} else { } else {
if conf.DatabaseConfig.Type == "UNSET" { switch conf.DatabaseConfig.Type {
// 未指定数据库时使用SQLite case "UNSET", "sqlite", "sqlite3":
// 未指定数据库或者明确指定为 sqlite 时,使用 SQLite3 数据库
db, err = gorm.Open("sqlite3", util.RelativePath(conf.DatabaseConfig.DBFile)) db, err = gorm.Open("sqlite3", util.RelativePath(conf.DatabaseConfig.DBFile))
} else { case "mysql":
db, err = gorm.Open(conf.DatabaseConfig.Type, fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", // 当前只支持 sqlite3 与 mysql 数据库
// TODO: import 其他 gorm 支持的主流数据库?否则直接 Open 没有任何意义。
// TODO: 数据库连接其他参数允许用户自定义?譬如编码更换为 utf8mb4 以支持表情。
db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
conf.DatabaseConfig.User, conf.DatabaseConfig.User,
conf.DatabaseConfig.Password, conf.DatabaseConfig.Password,
conf.DatabaseConfig.Host, conf.DatabaseConfig.Host,
conf.DatabaseConfig.Port, conf.DatabaseConfig.Port,
conf.DatabaseConfig.Name)) conf.DatabaseConfig.Name))
default:
util.Log().Panic("不支持数据库类型: %s", conf.DatabaseConfig.Type)
} }
} }
//db.SetLogger(util.Log())
if err != nil {
util.Log().Panic("连接数据库不成功, %s", err)
}
// 处理表前缀 // 处理表前缀
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string { gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return conf.DatabaseConfig.TablePrefix + defaultTableName return conf.DatabaseConfig.TablePrefix + defaultTableName
@ -53,11 +65,6 @@ func Init() {
db.LogMode(false) db.LogMode(false)
} }
//db.SetLogger(util.Log())
if err != nil {
util.Log().Panic("连接数据库不成功, %s", err)
}
//设置连接池 //设置连接池
//空闲 //空闲
db.DB().SetMaxIdleConns(50) db.DB().SetMaxIdleConns(50)

Loading…
Cancel
Save