job.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "kpt-pasture/config"
  6. "kpt-pasture/store/kptstore"
  7. "gitee.com/xuyiping_admin/pkg/cmd"
  8. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  9. "gitee.com/xuyiping_admin/pkg/xerr"
  10. "gitee.com/xuyiping_admin/pkg/xstore/database/migrator"
  11. "github.com/spf13/cobra"
  12. "go.uber.org/zap"
  13. )
  14. func init() {
  15. cmd.Instant(JobCmd, "db:migrate", taskDBMigrate, "数据库迁移-执行完立刻退出")
  16. }
  17. var JobCmd = &cobra.Command{
  18. Use: "job",
  19. Short: "内部一次性脚本",
  20. Run: func(cmd *cobra.Command, args []string) {
  21. fmt.Println("job called")
  22. },
  23. }
  24. // Migration record
  25. type Migration struct {
  26. Id int `xorm:"INT AUTOINCR NOTNULL PK"`
  27. Name string `xorm:"VARCHAR(1024) NOTNULL UNIQUE"`
  28. }
  29. // TableName migrations
  30. func (Migration) TableName() string {
  31. return "migrations"
  32. }
  33. func taskDBMigrate(ctx context.Context, args []string) error {
  34. cfg := config.Options()
  35. zaplog.Info("boot migrate")
  36. db := kptstore.MustMigrateStore(cfg)
  37. if err := migrator.AutoMigrateFiles(db, "../migrator"); err != nil {
  38. zaplog.Error("taskDBMigrate", zap.Any("err", err))
  39. panic(xerr.WithStack(err))
  40. }
  41. sqlDB, _ := db.DB()
  42. defer sqlDB.Close()
  43. zaplog.Info("migrate ok")
  44. return nil
  45. }