Add callback.go

This commit is contained in:
Jinzhu 2014-01-23 16:43:39 +08:00
parent 950518ae24
commit 6bb7c8b744
5 changed files with 65 additions and 10 deletions

View File

@ -1003,7 +1003,6 @@ db.Where("email = ?", "x@example.org").Attrs(User{RegisteredIp: "111.111.111.111
AfterSave
AfterCreate
AfterUpdate
SoftDelete
BeforeQuery
BeforeSave

55
callback.go Normal file
View File

@ -0,0 +1,55 @@
package gorm
import (
"fmt"
"time"
)
type callback struct {
Create []func()
Update []func()
Delete []func()
Query []func()
}
func (c *callback) RegisterCallback(typ string, fc func()) {
}
func query(db *DB) {
}
func save(db *DB) {
}
func create(db *DB) {
}
func update(db *DB) {
}
func Delete(scope *Scope) {
scope.CallMethod("BeforeDelete")
if !scope.HasError() {
if !scope.Search.unscope && scope.HasColumn("DeletedAt") {
scope.Raw(fmt.Sprintf("UPDATE %v SET deleted_at=%v %v", scope.Table(), scope.AddToVars(time.Now()), scope.CombinedSql()))
} else {
scope.Raw(fmt.Sprintf("DELETE FROM %v %v", scope.Table(), scope.CombinedSql()))
}
scope.Exec()
scope.CallMethod("AfterDelete")
}
}
var DefaultCallback = &callback{}
func init() {
DefaultCallback.Create().Before("Delete").After("Lalala").Register("delete", Delete)
DefaultCallback.Update().Before("Delete").After("Lalala").Remove("replace", Delete)
DefaultCallback.Delete().Before("Delete").After("Lalala").Replace("replace", Delete)
DefaultCallback.Query().Before("Delete").After("Lalala").Replace("replace", Delete)
}
// Scope
// HasError(), HasColumn(), CallMethod(), Raw(), Exec()
// TableName(), CombinedQuerySQL()

View File

@ -87,6 +87,8 @@ var (
)
func init() {
db.Debug().Model(User{}).RemoveIndex("name")
var err error
switch os.Getenv("GORM_DIALECT") {
case "mysql":

View File

@ -16,7 +16,6 @@ type Logger struct {
*log.Logger
}
//var defaultLogger = log.New(os.Stdout, "\r\n", 0)
var defaultLogger = Logger{log.New(os.Stdout, "\r\n", 0)}
// Format log

16
main.go
View File

@ -8,24 +8,24 @@ import (
type DB struct {
Value interface{}
Callbacks *callback
Error error
db sqlCommon
parent *DB
search *search
Error error
logMode int
logger logger
dialect dialect.Dialect
tagIdentifier string
singularTable bool
logger logger
logMode int
}
func Open(driver, source string) (db DB, err error) {
func Open(driver, source string) (DB, error) {
var err error
db := DB{dialect: dialect.New(driver), tagIdentifier: "sql", logger: defaultLogger}
db.db, err = sql.Open(driver, source)
db.dialect = dialect.New(driver)
db.tagIdentifier = "sql"
db.logger = defaultLogger
db.parent = &db
return
return db, err
}
func (s *DB) DB() *sql.DB {