initdb.go 1.3 KB

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