ferry/models/system/initdb.go
2023-11-28 22:18:28 +08:00

46 lines
999 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package system
import (
"ferry/global/orm"
"fmt"
"io/ioutil"
"strings"
)
/*
@Author : lanyulei
*/
func InitDb() error {
filePath := "config/db.sql"
sql, err := Ioutil(filePath)
if err != nil {
fmt.Println("数据库基础数据初始化脚本读取失败!原因:", err.Error())
return err
}
sqlList := strings.Split(sql, ";")
for _, sql := range sqlList {
if strings.Contains(sql, "--") {
fmt.Println(sql)
continue
}
sqlValue := strings.Replace(sql+";", "\n", "", 1)
if err = orm.Eloquent.Exec(sqlValue).Error; err != nil {
if !strings.Contains(err.Error(), "Query was empty") {
return err
}
}
}
return nil
}
func Ioutil(name string) (string, error) {
if contents, err := ioutil.ReadFile(name); err == nil {
//因为contents是[]byte类型直接转换成string类型后会多一行空格,需要使用strings.Replace替换换行符
result := strings.Replace(string(contents), "\n", "", 1)
return result, nil
} else {
return "", err
}
}