Created
October 19, 2016 13:17
-
-
Save sakuemon/8d5e8d9c08bb82e141e8cf010e8c664f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tx | |
import "fmt" | |
type DB struct { | |
committed bool | |
} | |
func NewDB() *DB { | |
db := DB{ | |
committed: true, | |
} | |
return &db | |
} | |
func (db *DB) Begin() *DB { | |
return db | |
} | |
func (db *DB) Commit() *DB { | |
db.committed = false | |
return db | |
} | |
func (db *DB) Rollback() *DB { | |
return db | |
} | |
func (db *DB) GetErrors() (*DB, []error) { | |
return db, []error{} | |
} | |
func Transaction(db *DB, txFunc func(*DB) error) []error { | |
tx, errs := db.Begin().GetErrors() | |
if len(errs) != 0 { | |
return errs | |
} | |
defer func() { | |
if p := recover(); p != nil { | |
switch p := p.(type) { | |
case error: | |
errs = []error{p} | |
default: | |
errs = []error{fmt.Errorf("%s", p)} | |
} | |
} | |
if len(errs) != 0 { | |
tx.Rollback() | |
return | |
} | |
_, errs = tx.Commit().GetErrors() | |
}() | |
return []error{txFunc(tx)} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment