1
0
mirror of https://github.com/beego/bee.git synced 2024-12-23 16:40:50 +00:00
bee/internal/app/module/beegopro/migration.go

80 lines
1.7 KiB
Go
Raw Normal View History

2020-07-04 14:58:03 +00:00
package beegopro
import (
"database/sql"
beeLogger "github.com/beego/bee/logger"
"github.com/beego/bee/utils"
"io/ioutil"
"path/filepath"
2020-07-11 09:44:39 +00:00
"strings"
2020-07-04 14:58:03 +00:00
)
var SQL utils.DocValue
2020-07-11 09:44:39 +00:00
var SQLMode utils.DocValue
var SQLModePath utils.DocValue
var (
SQLModeUp = "up"
SQLModeDown = "down"
)
2020-07-04 14:58:03 +00:00
func (c *Container) Migration(args []string) {
2020-07-05 06:54:26 +00:00
c.initUserOption()
db, err := sql.Open(c.UserOption.Driver, c.UserOption.Dsn)
2020-07-04 14:58:03 +00:00
if err != nil {
2020-07-05 06:54:26 +00:00
beeLogger.Log.Fatalf("Could not connect to '%s' database using '%s': %s", c.UserOption.Driver, c.UserOption.Dsn, err)
2020-07-04 14:58:03 +00:00
return
}
defer db.Close()
2020-07-11 09:44:39 +00:00
switch SQLMode.String() {
case SQLModeUp:
doByMode(db, "up.sql")
case SQLModeDown:
doByMode(db, "down.sql")
default:
doBySqlFile(db)
}
}
func doBySqlFile(db *sql.DB) {
fileName := SQL.String()
if !utils.IsExist(fileName) {
beeLogger.Log.Fatalf("sql mode path not exist, path %s", SQL.String())
}
doDb(db, fileName)
}
2020-07-04 14:58:03 +00:00
2020-07-11 09:44:39 +00:00
func doByMode(db *sql.DB, suffix string) {
pathName := SQLModePath.String()
if !utils.IsExist(pathName) {
beeLogger.Log.Fatalf("sql mode path not exist, path %s", SQLModePath.String())
}
rd, err := ioutil.ReadDir(pathName)
if err != nil {
beeLogger.Log.Fatalf("read dir err, path %s, err %s", pathName, err)
}
for _, fi := range rd {
if !fi.IsDir() {
if !strings.HasSuffix(fi.Name(), suffix) {
continue
}
doDb(db, filepath.Join(pathName, fi.Name()))
}
}
}
func doDb(db *sql.DB, filePath string) {
absFile, _ := filepath.Abs(filePath)
content, err := ioutil.ReadFile(filePath)
2020-07-04 14:58:03 +00:00
if err != nil {
beeLogger.Log.Errorf("read file err %s, abs file %s", err, absFile)
}
2020-07-11 09:44:39 +00:00
_, err = db.Exec(string(content))
2020-07-04 14:58:03 +00:00
if err != nil {
beeLogger.Log.Errorf("db exec err %s", err)
}
2020-07-11 09:44:39 +00:00
beeLogger.Log.Infof("db exec info %s", filePath)
2020-07-04 14:58:03 +00:00
}