auto migrate

This commit is contained in:
Jinzhu 2013-11-07 09:09:54 +08:00
parent 6d7d892af7
commit 5da8461161
5 changed files with 21 additions and 4 deletions

View File

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

8
do.go
View File

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

View File

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

View File

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

View File

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