106 lines
2.8 KiB
Go
106 lines
2.8 KiB
Go
package main
|
||
|
||
import (
|
||
"fmt"
|
||
"log"
|
||
|
||
"git.toowon.com/jimmy/go-common/migration"
|
||
"gorm.io/driver/sqlite"
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
func main() {
|
||
// 初始化数据库连接(使用SQLite作为示例)
|
||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||
if err != nil {
|
||
log.Fatal("Failed to connect to database:", err)
|
||
}
|
||
|
||
// 创建迁移器
|
||
migrator := migration.NewMigrator(db)
|
||
|
||
// 添加一些迁移
|
||
migrator.AddMigrations(
|
||
migration.Migration{
|
||
Version: "20240101000001",
|
||
Description: "create_users_table",
|
||
Up: func(db *gorm.DB) error {
|
||
return db.Exec(`
|
||
CREATE TABLE users (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
name VARCHAR(255) NOT NULL,
|
||
email VARCHAR(255) UNIQUE NOT NULL
|
||
)
|
||
`).Error
|
||
},
|
||
Down: func(db *gorm.DB) error {
|
||
return db.Exec("DROP TABLE IF EXISTS users").Error
|
||
},
|
||
},
|
||
migration.Migration{
|
||
Version: "20240101000002",
|
||
Description: "add_created_at_to_users",
|
||
Up: func(db *gorm.DB) error {
|
||
return db.Exec("ALTER TABLE users ADD COLUMN created_at DATETIME").Error
|
||
},
|
||
Down: func(db *gorm.DB) error {
|
||
return db.Exec("ALTER TABLE users DROP COLUMN created_at").Error
|
||
},
|
||
},
|
||
)
|
||
|
||
// 执行迁移
|
||
fmt.Println("=== Executing migrations ===")
|
||
err = migrator.Up()
|
||
if err != nil {
|
||
log.Fatal("Failed to run migrations:", err)
|
||
}
|
||
|
||
// 查看状态
|
||
fmt.Println("\n=== Migration status ===")
|
||
status, err := migrator.Status()
|
||
if err != nil {
|
||
log.Fatal("Failed to get status:", err)
|
||
}
|
||
for _, s := range status {
|
||
fmt.Printf("Version: %s, Description: %s, Applied: %v\n",
|
||
s.Version, s.Description, s.Applied)
|
||
}
|
||
|
||
// 示例1:仅清空迁移记录(不回滚数据库变更)
|
||
fmt.Println("\n=== Example 1: Reset migration records only ===")
|
||
fmt.Println("Note: This only clears records, not database changes")
|
||
// 直接调用(需要确认标志)
|
||
// err = migrator.Reset(true)
|
||
// if err != nil {
|
||
// log.Fatal("Failed to reset:", err)
|
||
// }
|
||
|
||
// 交互式确认(推荐)
|
||
// 取消注释下面的代码来测试交互式重置
|
||
// err = migrator.ResetWithConfirm()
|
||
// if err != nil {
|
||
// log.Fatal("Failed to reset with confirm:", err)
|
||
// }
|
||
|
||
// 示例2:回滚所有迁移并清空记录
|
||
fmt.Println("\n=== Example 2: Reset all migrations (rollback + clear records) ===")
|
||
fmt.Println("Note: This will rollback all migrations and clear records")
|
||
// 直接调用(需要确认标志)
|
||
// err = migrator.ResetAll(true)
|
||
// if err != nil {
|
||
// log.Fatal("Failed to reset all:", err)
|
||
// }
|
||
|
||
// 交互式确认(推荐)
|
||
// 取消注释下面的代码来测试交互式重置
|
||
// err = migrator.ResetAllWithConfirm()
|
||
// if err != nil {
|
||
// log.Fatal("Failed to reset all with confirm:", err)
|
||
// }
|
||
|
||
fmt.Println("\nNote: Reset functions are commented out for safety.")
|
||
fmt.Println("Uncomment the code above to test reset functionality.")
|
||
}
|
||
|