Skip to content

Commit

Permalink
fix check database if exist
Browse files Browse the repository at this point in the history
  • Loading branch information
zhmin authored and ouqiang committed Jul 11, 2018
1 parent c6b3cf1 commit 370645f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
10 changes: 0 additions & 10 deletions internal/models/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}{
Expand All @@ -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版本不支持升级
Expand Down
26 changes: 21 additions & 5 deletions internal/routers/install/install.go
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 370645f

Please sign in to comment.