AutoMigrate accepts structs

This commit is contained in:
Jinzhu 2014-08-20 11:56:39 +08:00
parent 10668ee323
commit 14fdbdd965
3 changed files with 9 additions and 28 deletions

View File

@ -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.

View File

@ -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 {

View File

@ -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))
}
}