initdb.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package models
  2. import (
  3. "fmt"
  4. "go-admin/common/global"
  5. "io/ioutil"
  6. "log"
  7. "strings"
  8. "gorm.io/gorm"
  9. )
  10. func InitDb(db *gorm.DB) (err error) {
  11. filePath := "config/db.sql"
  12. err = ExecSql(db, filePath)
  13. if global.Driver == "postgres" {
  14. filePath = "config/pg.sql"
  15. err = ExecSql(db, filePath)
  16. }
  17. return err
  18. }
  19. func ExecSql(db *gorm.DB, filePath string) error {
  20. sql, err := Ioutil(filePath)
  21. if err != nil {
  22. fmt.Println("数据库基础数据初始化脚本读取失败!原因:", err.Error())
  23. return err
  24. }
  25. sqlList := strings.Split(sql, ";")
  26. for i := 0; i < len(sqlList)-1; i++ {
  27. if strings.Contains(sqlList[i], "--") {
  28. fmt.Println(sqlList[i])
  29. continue
  30. }
  31. sql := strings.Replace(sqlList[i]+";", "\n", " ", -1)
  32. sql = strings.TrimSpace(sql)
  33. if err = db.Exec(sql).Error; err != nil {
  34. log.Printf("error sql: %s", sql)
  35. if !strings.Contains(err.Error(), "Query was empty") {
  36. return err
  37. }
  38. }
  39. }
  40. return nil
  41. }
  42. func Ioutil(filePath string) (string, error) {
  43. if contents, err := ioutil.ReadFile(filePath); err == nil {
  44. //因为contents是[]byte类型,直接转换成string类型后会多一行空格,需要使用strings.Replace替换换行符
  45. result := strings.Replace(string(contents), "\n", "", 1)
  46. fmt.Println("Use ioutil.ReadFile to read a file:", result)
  47. return result, nil
  48. } else {
  49. return "", err
  50. }
  51. }