Ver código fonte

feat(command): migrate fresh

runningwater 7 meses atrás
pai
commit
07e92dd592
4 arquivos alterados com 93 adições e 0 exclusões
  1. 1 0
      README.md
  2. 9 0
      app/cmd/migrate.go
  3. 64 0
      pkg/database/database.go
  4. 19 0
      pkg/migrate/migrator.go

+ 1 - 0
README.md

@@ -72,6 +72,7 @@ UNIQUE KEY `migration` (`migration`)
 
 #### 🚀 新功能
 
+- *(command)* Migrate fresh
 - *(command)* Migrate reset and migrate refresh
 - *(command)* Migrate rollback 命令
 - *(command)* Make migration 命令

+ 9 - 0
app/cmd/migrate.go

@@ -45,6 +45,14 @@ var CmdMigrateRefresh = &cobra.Command{
 	},
 }
 
+var CmdMigrateFresh = &cobra.Command{
+	Use:   "fresh",
+	Short: "Drop all tables and re-run all migrations",
+	Run: func(cmd *cobra.Command, args []string) {
+		migrator().Fresh()
+	},
+}
+
 // 初始化命令
 func init() {
 	CmdMigrate.AddCommand(
@@ -52,6 +60,7 @@ func init() {
 		CmdMigrateRollback,
 		CmdMigrateReset,
 		CmdMigrateRefresh,
+		CmdMigrateFresh,
 	)
 }
 

+ 64 - 0
pkg/database/database.go

@@ -7,6 +7,7 @@ import (
 	"database/sql"
 	"fmt"
 
+	"github.com/runningwater/gohub/pkg/config"
 	"gorm.io/gorm"
 	gormlgger "gorm.io/gorm/logger"
 )
@@ -31,3 +32,66 @@ func Connect(dbConfig gorm.Dialector, _logger gormlgger.Interface) {
 		fmt.Println("数据库连接失败", err.Error())
 	}
 }
+
+func CurrentDatabase() string {
+	return DB.Migrator().CurrentDatabase()
+}
+func DeleteAllTables() error {
+	var err error
+
+	switch config.Get("database.connection") {
+	case "mysql":
+		err = deleteMySQLTables()
+	case "sqlite":
+		err = deleteAllSQLiteTables()
+	default:
+		err = fmt.Errorf("不支持的数据库类型: %s", config.Get("database.connection"))
+	}
+
+	return err
+}
+
+func deleteMySQLTables() error {
+	dbname := CurrentDatabase()
+	tables := []string{}
+
+	err := DB.Table("information_schema.tables").
+		Where("table_schema = ?", dbname).
+		Pluck("table_name", &tables).Error
+	if err != nil {
+		return err
+	}
+
+	// 暂时关闭外键检测
+	DB.Exec("SET FOREIGN_KEY_CHECKS = 0;")
+
+	// 删除所有表
+	for _, table := range tables {
+		if err := DB.Migrator().DropTable(table); err != nil {
+			return err
+		}
+	}
+	// 重新启用外键检测
+	DB.Exec("SET FOREIGN_KEY_CHECKS = 1;")
+
+	return nil
+}
+
+func deleteAllSQLiteTables() error {
+	tables := []string{}
+
+	err := DB.Raw("SELECT name FROM sqlite_master WHERE type='table'").
+		Pluck("name", &tables).Error
+	if err != nil {
+		return err
+	}
+
+	// 删除所有表
+	for _, table := range tables {
+		if err := DB.Migrator().DropTable(table); err != nil {
+			return err
+		}
+	}
+
+	return nil
+}

+ 19 - 0
pkg/migrate/migrator.go

@@ -114,6 +114,25 @@ func (m *Migrator) Refresh() {
 	m.Up()
 }
 
+// Fresh Drop 所有的表, 并重新执行所有的迁移操作
+func (m *Migrator) Fresh() {
+
+	// 获取数据库名称,用以提示
+	dbname := database.CurrentDatabase()
+
+	// 删除所有表
+	err := database.DeleteAllTables()
+	console.ExitIf(err)
+	console.Success("database " + dbname + " cleared")
+
+	// 重新创建 migrates 表
+	m.createMigrationsTable()
+	console.Success("migrations table created")
+
+	// 重新执行所有的迁移操作
+	m.Up()
+}
+
 // 回滚迁移操作
 func (m *Migrator) rollbackMigrations(migrations []Migration) bool {