Skip to content

Instantly share code, notes, and snippets.

@sakuemon
Created October 19, 2016 13:17
Show Gist options
  • Save sakuemon/8d5e8d9c08bb82e141e8cf010e8c664f to your computer and use it in GitHub Desktop.
Save sakuemon/8d5e8d9c08bb82e141e8cf010e8c664f to your computer and use it in GitHub Desktop.
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