You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.3 KiB

4 years ago
4 years ago
  1. package service
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "gin-vue-admin/global"
  6. "gin-vue-admin/model"
  7. "gin-vue-admin/model/request"
  8. "gin-vue-admin/source"
  9. "github.com/spf13/viper"
  10. )
  11. //@author: [songzhibin97](https://github.com/songzhibin97)
  12. //@function: writeConfig
  13. //@description: 回写配置
  14. //@param:
  15. //@return: error
  16. func writeConfig(viper *viper.Viper, conf map[string]interface{}) error {
  17. for k, v := range conf {
  18. viper.Set(k, v)
  19. }
  20. return viper.WriteConfig()
  21. }
  22. //@author: [songzhibin97](https://github.com/songzhibin97)
  23. //@function: createTable
  24. //@description: 创建数据库(mysql)
  25. //@param: dsn string, driver string, createSql
  26. //@return: error
  27. func createTable(dsn string, driver string, createSql string) error {
  28. db, err := sql.Open(driver, dsn)
  29. if err != nil {
  30. return err
  31. }
  32. defer db.Close()
  33. if err = db.Ping(); err != nil {
  34. return err
  35. }
  36. _, err = db.Exec(createSql)
  37. return err
  38. }
  39. func initDB(InitDBFunctions ...model.InitDBFunc) (err error) {
  40. for _, v := range InitDBFunctions {
  41. err = v.Init()
  42. if err != nil {
  43. return err
  44. }
  45. }
  46. return nil
  47. }
  48. //@author: [songzhibin97](https://github.com/songzhibin97)
  49. //@function: InitDB
  50. //@description: 创建数据库并初始化
  51. //@param: authorityId string
  52. //@return: err error, treeMap map[string][]model.SysMenu
  53. func InitDB(conf request.InitDB) error {
  54. if conf.Host == "" {
  55. conf.Host = "127.0.0.1"
  56. }
  57. if conf.Port == "" {
  58. conf.Port = "3306"
  59. }
  60. dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/", conf.UserName, conf.Password, conf.Host, conf.Port)
  61. fmt.Println(dsn)
  62. createSql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;", conf.DBName)
  63. if err := createTable(dsn, "mysql", createSql); err != nil {
  64. return err
  65. }
  66. setting := map[string]interface{}{
  67. "mysql.path": fmt.Sprintf("%s:%s", conf.Host, conf.Port),
  68. "mysql.db-name": conf.DBName,
  69. "mysql.username": conf.UserName,
  70. "mysql.password": conf.Password,
  71. }
  72. if err := writeConfig(global.GVA_VP, setting); err != nil {
  73. return err
  74. }
  75. err := initDB(source.Admin,
  76. source.Api,
  77. source.AuthorityMenu,
  78. source.Authority,
  79. source.AuthoritiesMenus,
  80. source.Casbin,
  81. source.DataAuthorities,
  82. source.Dictionary,
  83. source.DictionaryDetail,
  84. source.File,
  85. source.BaseMenu,
  86. source.Workflow)
  87. if err!=nil {
  88. return err
  89. }
  90. return nil
  91. }