diff --git a/README.md b/README.md index ea2fe2ae..d3dfdd11 100644 --- a/README.md +++ b/README.md @@ -1003,7 +1003,6 @@ db.Where("email = ?", "x@example.org").Attrs(User{RegisteredIp: "111.111.111.111 AfterSave AfterCreate AfterUpdate - SoftDelete BeforeQuery BeforeSave diff --git a/callback.go b/callback.go new file mode 100644 index 00000000..4bbcd7f8 --- /dev/null +++ b/callback.go @@ -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() diff --git a/gorm_test.go b/gorm_test.go index 21871db7..dc27613b 100644 --- a/gorm_test.go +++ b/gorm_test.go @@ -87,6 +87,8 @@ var ( ) func init() { + db.Debug().Model(User{}).RemoveIndex("name") + var err error switch os.Getenv("GORM_DIALECT") { case "mysql": diff --git a/logger.go b/logger.go index 2e43e358..2c76987e 100644 --- a/logger.go +++ b/logger.go @@ -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 diff --git a/main.go b/main.go index 538ae182..214a9c31 100644 --- a/main.go +++ b/main.go @@ -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 {