From 5da846116106b25d145648b1c7730e5512870302 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 7 Nov 2013 09:09:54 +0800 Subject: [PATCH] auto migrate --- chain.go | 5 +++++ do.go | 8 ++++++++ gorm_test.go | 4 ++++ main.go | 4 ++++ model.go | 4 ---- 5 files changed, 21 insertions(+), 4 deletions(-) diff --git a/chain.go b/chain.go index 8ccf4d7b..87c410bd 100644 --- a/chain.go +++ b/chain.go @@ -245,6 +245,11 @@ func (s *Chain) DropTable(value interface{}) *Chain { return s } +func (s *Chain) AutoMigrate(value interface{}) *Chain { + s.do(value).autoMigrate().exec() + return s +} + func (s *Chain) Unscoped() *Chain { s.unscoped = true return s diff --git a/do.go b/do.go index 44bedf22..b20c0841 100644 --- a/do.go +++ b/do.go @@ -726,6 +726,14 @@ func (s *Do) dropTable() *Do { return s } +func (s *Do) autoMigrate() *Do { + sql := fmt.Sprintf("SELECT column_name, data_type FROM information_schema.columns WHERE table_name = %v", s.tableName()) + for _, field := range s.model.fields("other") { + s.sql = fmt.Sprintf(sql+"and column_name = %v", field.DbName) + } + return s +} + func (s *Do) initializeWithSearchCondition() { m := Model{data: s.value, driver: s.driver} diff --git a/gorm_test.go b/gorm_test.go index f6697399..a1287afe 100644 --- a/gorm_test.go +++ b/gorm_test.go @@ -1235,3 +1235,7 @@ func TestTableName(t *testing.T) { t.Errorf("Cart's singular table name should be shopping_cart") } } + +func TestAutoMigration(t *testing.T) { + db.AutoMigrate(Address{}) +} diff --git a/main.go b/main.go index 8bf63aea..55efbf0e 100644 --- a/main.go +++ b/main.go @@ -114,3 +114,7 @@ func (s *DB) CreateTable(value interface{}) *Chain { func (s *DB) DropTable(value interface{}) *Chain { return s.buildChain().DropTable(value) } + +func (s *DB) AutoMigrate(value interface{}) *Chain { + return s.buildChain().AutoMigrate(value) +} diff --git a/model.go b/model.go index c522734c..9751908e 100644 --- a/model.go +++ b/model.go @@ -331,10 +331,6 @@ func (m *Model) returningStr() (str string) { return } -func (m *Model) missingColumns() (results []string) { - return -} - func (m *Model) setValueByColumn(name string, value interface{}, out interface{}) { data := reflect.Indirect(reflect.ValueOf(out)) setFieldValue(data.FieldByName(snakeToUpperCamel(name)), value)