From 14fdbdd9654a2faf706e51f23aa66b9f1b746cfc Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 20 Aug 2014 11:56:39 +0800 Subject: [PATCH] AutoMigrate accepts structs --- README.md | 1 + main.go | 8 ++++++-- migration_test.go | 28 ++-------------------------- 3 files changed, 9 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 11ced96f..91751944 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,7 @@ db.DropTableIfExists(User{}) // Automating Migration db.AutoMigrate(User{}) +db.AutoMigrate(User{}, Proudct{}, Order{}) // Feel free to change your struct, AutoMigrate will keep your database up-to-date. // Fyi, AutoMigrate will only *add new columns*, it won't update column's type or delete unused columns, to make sure your data is safe. diff --git a/main.go b/main.go index abea9263..cee5f59c 100644 --- a/main.go +++ b/main.go @@ -344,8 +344,12 @@ func (s *DB) DropTableIfExists(value interface{}) *DB { return s.clone().NewScope(value).dropTableIfExists().db } -func (s *DB) AutoMigrate(value interface{}) *DB { - return s.clone().NewScope(value).autoMigrate().db +func (s *DB) AutoMigrate(values ...interface{}) *DB { + db := s.clone() + for _, value := range values { + db = db.NewScope(value).autoMigrate().db + } + return db } func (s *DB) ModifyColumn(column string, typ string) *DB { diff --git a/migration_test.go b/migration_test.go index 008329ae..1dfb4d10 100644 --- a/migration_test.go +++ b/migration_test.go @@ -25,35 +25,11 @@ func runMigration() { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } - if err := db.CreateTable(&User{}).Error; err != nil { + if err := db.CreateTable(User{}).Error; err != nil { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } - if err := db.CreateTable(&Product{}).Error; err != nil { - panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) - } - - if err := db.CreateTable(Email{}).Error; err != nil { - panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) - } - - if err := db.AutoMigrate(Address{}).Error; err != nil { - panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) - } - - if err := db.AutoMigrate(&CreditCard{}).Error; err != nil { - panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) - } - - if err := db.AutoMigrate(Company{}).Error; err != nil { - panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) - } - - if err := db.AutoMigrate(Role{}).Error; err != nil { - panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) - } - - if err := db.AutoMigrate(Language{}).Error; err != nil { + if err := db.AutoMigrate(&Product{}, Email{}, Address{}, CreditCard{}, Company{}, Role{}, Language{}).Error; err != nil { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } }