Add callbacks support

This commit is contained in:
Jinzhu 2013-10-27 14:51:23 +08:00
parent 97f234e481
commit b551fee276
3 changed files with 29 additions and 1 deletions

View File

@ -122,6 +122,17 @@ func (m *Model) TableName() string {
return reg.ReplaceAllString(toSnake(t.Name()), "s")
}
func (model *Model) callMethod(method string) error {
fm := reflect.ValueOf(model).MethodByName(method)
if fm.IsValid() {
v := fm.Call([]reflect.Value{})
if verr, ok := v[0].Interface().(error); ok {
return verr
}
}
return nil
}
func (model *Model) MissingColumns() (results []string) {
return
}

2
orm.go
View File

@ -118,7 +118,7 @@ func (s *Orm) Save(value interface{}) *Orm {
}
func (s *Orm) Delete(value interface{}) *Orm {
s.explain(value, "Delete").Exec()
s.explain(value, "Delete").delete(value)
return s
}

17
sql.go
View File

@ -129,6 +129,9 @@ func (s *Orm) createSql(value interface{}) {
func (s *Orm) create(value interface{}) {
var id int64
s.err(s.model.callMethod("BeforeCreate"))
s.err(s.model.callMethod("BeforeSave"))
if s.driver == "postgres" {
s.err(s.db.QueryRow(s.Sql, s.SqlVars...).Scan(&id))
} else {
@ -139,6 +142,9 @@ func (s *Orm) create(value interface{}) {
s.err(err)
}
s.err(s.model.callMethod("AfterCreate"))
s.err(s.model.callMethod("AfterSave"))
result := reflect.ValueOf(s.model.Data).Elem()
result.FieldByName(s.model.PrimaryKey()).SetInt(id)
}
@ -161,7 +167,11 @@ func (s *Orm) updateSql(value interface{}) {
}
func (s *Orm) update(value interface{}) {
s.err(s.model.callMethod("BeforeUpdate"))
s.err(s.model.callMethod("BeforeSave"))
s.Exec()
s.err(s.model.callMethod("AfterUpdate"))
s.err(s.model.callMethod("AfterSave"))
return
}
@ -169,6 +179,13 @@ func (s *Orm) deleteSql(value interface{}) {
s.Sql = fmt.Sprintf("DELETE FROM %v %v", s.TableName, s.combinedSql())
return
}
func (s *Orm) delete(value interface{}) {
s.err(s.model.callMethod("BeforeDelete"))
s.Exec()
s.err(s.model.callMethod("AfterDelete"))
}
func (s *Orm) buildWhereCondition(clause map[string]interface{}) string {
str := "( " + clause["query"].(string) + " )"