make_migration.go 1.0 KB

123456789101112131415161718192021222324252627282930
  1. package make
  2. import (
  3. "github.com/runningwater/gohub/pkg/app"
  4. "github.com/runningwater/gohub/pkg/console"
  5. "github.com/spf13/cobra"
  6. )
  7. var CmdMakeMigration = &cobra.Command{
  8. Use: "migration",
  9. Short: "Create a migration file, example: make migration add_users_table",
  10. Run: runMakeMigration,
  11. Args: cobra.ExactArgs(1), // 只允许且必须传 1 个参数
  12. }
  13. func runMakeMigration(cmd *cobra.Command, args []string) {
  14. // 格式:2023_01_30_141939_create_users_table.go
  15. timeStr := app.TimenowInTimezone().Format("2006_01_02_150405")
  16. // 第二个参数是迁移名称,用于生成迁移文件的文件名
  17. model := makeModelFromString(args[0])
  18. fileName := timeStr + "_" + model.PackageName
  19. // 拼接生成的迁移文件的路径
  20. filePath := "database/migrations/" + fileName + ".go"
  21. // 基于 tpls 目录创建文件
  22. createFileFromTpl(filePath, "migration", model, map[string]string{"{{FileName}}": fileName})
  23. // 输出信息
  24. console.Success("Migration file created, after modify it, use `migrate up` to migrate database.")
  25. }