server.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. package migrate
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strconv"
  6. "text/template"
  7. "time"
  8. "github.com/go-admin-team/go-admin-core/sdk"
  9. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  10. "github.com/pkg/errors"
  11. "github.com/go-admin-team/go-admin-core/config/source/file"
  12. "github.com/spf13/cobra"
  13. "go-admin/cmd/migrate/migration"
  14. _ "go-admin/cmd/migrate/migration/version"
  15. extConfig "go-admin/config"
  16. "github.com/go-admin-team/go-admin-core/sdk/config"
  17. _ "go-admin/cmd/migrate/migration/version-local"
  18. "go-admin/common/database"
  19. "go-admin/common/models"
  20. "go-admin/common/olap"
  21. )
  22. var (
  23. configYml string
  24. generate bool
  25. goAdmin bool
  26. host string
  27. StartCmd = &cobra.Command{
  28. Use: "migrate",
  29. Short: "Initialize the database",
  30. Example: "go-admin migrate -c config/settings.yml",
  31. PreRun: func(cmd *cobra.Command, args []string) {
  32. // 注入配置扩展项, 后面的clickhouse迁移需要这些config
  33. config.ExtendConfig = &extConfig.ExtConfig
  34. },
  35. Run: func(cmd *cobra.Command, args []string) {
  36. run()
  37. },
  38. }
  39. )
  40. // fixme 在您看不见代码的时候运行迁移,我觉得是不安全的,所以编译后最好不要去执行迁移
  41. func init() {
  42. StartCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "config/settings.yml", "Start server with provided configuration file")
  43. StartCmd.PersistentFlags().BoolVarP(&generate, "generate", "g", false, "generate migration file")
  44. StartCmd.PersistentFlags().BoolVarP(&goAdmin, "goAdmin", "a", false, "generate go-admin migration file")
  45. StartCmd.PersistentFlags().StringVarP(&host, "domain", "d", "*", "select tenant host")
  46. }
  47. func run() {
  48. if !generate {
  49. fmt.Println(`start init`)
  50. //1. 读取配置
  51. config.Setup(
  52. file.NewSource(file.WithPath(configYml)),
  53. initDB,
  54. )
  55. } else {
  56. fmt.Println(`generate migration file`)
  57. _ = genFile()
  58. }
  59. }
  60. func migrateModel() error {
  61. if host == "" {
  62. host = "*"
  63. }
  64. db := sdk.Runtime.GetDbByKey(host)
  65. if config.DatabasesConfig[host].Driver == "mysql" {
  66. //初始化数据库时候用
  67. db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
  68. }
  69. err := db.Debug().AutoMigrate(&models.Migration{})
  70. if err != nil {
  71. return err
  72. }
  73. migration.Migrate.SetDb(db.Debug())
  74. migration.Migrate.Migrate()
  75. return err
  76. }
  77. func migrateClickhouseModel() error {
  78. db := olap.GetClickhouseOrm()
  79. if err := db.Exec(`CREATE TABLE if not exists otel.sys_migration_local on cluster default (
  80. version String,
  81. apply_time DateTime64(3)
  82. ) ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 8192`).Error; err != nil {
  83. return errors.Wrap(err, "clickhouse生成sys_migration_local 失败")
  84. }
  85. if err := db.Exec(`create table if not exists otel.sys_migration on cluster default(
  86. version String,
  87. apply_time DateTime64(3)
  88. ) engine = Distributed('default', 'otel', 'sys_migration_local', cityHash64(version))`).Error; err != nil {
  89. return errors.Wrap(err, "clickhouse生成sys_migration分布式表失败")
  90. }
  91. err := db.Debug().AutoMigrate(&models.Migration{})
  92. if err != nil {
  93. return errors.Wrap(err, "auto migrate faild")
  94. }
  95. migration.Migrate.SetDb(db.Debug())
  96. migration.Migrate.Migrate()
  97. return err
  98. }
  99. func initDB() {
  100. //3. 初始化数据库链接
  101. database.Setup()
  102. // olap.Setup()
  103. //4. 数据库迁移
  104. fmt.Println("数据库迁移开始")
  105. _ = migrateModel()
  106. fmt.Println(`数据库基础数据初始化成功`)
  107. // fmt.Printf("数据库clickhouse迁移开始")
  108. // if err := migrateClickhouseModel(); err != nil {
  109. // panic(err)
  110. // }
  111. // fmt.Printf("数据库clickhouse迁移成功")
  112. }
  113. func genFile() error {
  114. t1, err := template.ParseFiles("template/migrate.template")
  115. if err != nil {
  116. return err
  117. }
  118. m := map[string]string{}
  119. m["GenerateTime"] = strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
  120. m["Package"] = "version_local"
  121. if goAdmin {
  122. m["Package"] = "version"
  123. }
  124. var b1 bytes.Buffer
  125. if err = t1.Execute(&b1, m); err != nil {
  126. return err
  127. }
  128. if goAdmin {
  129. pkg.FileCreate(b1, "./cmd/migrate/migration/version/"+m["GenerateTime"]+"_migrate.go")
  130. } else {
  131. pkg.FileCreate(b1, "./cmd/migrate/migration/version-local/"+m["GenerateTime"]+"_migrate.go")
  132. }
  133. return nil
  134. }