fix check database if exist

pull/109/head
zhmin 2018-07-11 17:50:20 +08:00 committed by qiang.ou
parent c6b3cf1509
commit 370645fca8
2 changed files with 21 additions and 15 deletions

View File

@ -13,9 +13,6 @@ type Migration struct{}
// 首次安装, 创建数据库表
func (migration *Migration) Install(dbName string) error {
if !isDatabaseExist(dbName) {
return errors.New("数据库不存在")
}
setting := new(Setting)
task := new(Task)
tables := []interface{}{
@ -39,13 +36,6 @@ func (migration *Migration) Install(dbName string) error {
return nil
}
// 判断数据库是否存在
func isDatabaseExist(name string) bool {
_, err := Db.Exec("use ?", name)
return err != nil
}
// 迭代升级数据库, 新建表、新增字段等
func (migration *Migration) Upgrade(oldVersionId int) {
// v1.2版本不支持升级

View File

@ -1,9 +1,12 @@
package install
import (
"errors"
"fmt"
"strconv"
"github.com/go-sql-driver/mysql"
"github.com/lib/pq"
"github.com/go-macaron/binding"
"github.com/ouqiang/gocron/internal/models"
"github.com/ouqiang/gocron/internal/modules/app"
@ -49,7 +52,7 @@ func Store(ctx *macaron.Context, form InstallForm) string {
}
err := testDbConnection(form)
if err != nil {
return json.CommonFailure("数据库连接失败", err)
return json.CommonFailure(err.Error())
}
// 写入数据库配置
err = writeConfig(form)
@ -144,12 +147,25 @@ func testDbConnection(form InstallForm) error {
s.Db.Database = form.DbName
s.Db.Charset = "utf8"
db, err := models.CreateTmpDb(&s)
if err != nil {
return err
}
defer db.Close()
err = db.Ping()
if s.Db.Engine == "postgres" && err != nil {
msg := "数据库连接失败"
pgError, _ := err.(*pq.Error)
if pgError.Code == "3D000" {
msg = "数据库不存在"
}
return errors.New(msg)
}
if s.Db.Engine == "mysql" && err != nil {
msg := "数据库连接失败"
mysqlError, _ := err.(*mysql.MySQLError)
if mysqlError.Number == 1049 {
msg = "数据库不存在"
}
return errors.New(msg)
}
return err