Last active
May 29, 2023 10:21
-
-
Save vurihuang/1a49fa23f4d71ca29b4d96f5cbc8c8ab to your computer and use it in GitHub Desktop.
go orm with transaction.
This file contains 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 main | |
import ( | |
"errors" | |
"fmt" | |
_ "github.com/go-sql-driver/mysql" | |
"github.com/jinzhu/gorm" | |
) | |
var db *gorm.DB | |
// TransactionFunc . | |
type TransactionFunc func(tx *gorm.DB) error | |
// DoInTransaction . | |
func DoInTransaction(db *gorm.DB, fn TransactionFunc) error { | |
tx := db.Begin() | |
if tx.Error != nil { | |
return tx.Error | |
} | |
err := fn(tx) | |
if err != nil { | |
if e := tx.Rollback().Error; e != nil { | |
return e | |
} | |
return err | |
} | |
if err = tx.Commit().Error; err != nil { | |
return err | |
} | |
return nil | |
} | |
// User . | |
type User struct { | |
ID int `gorm:"primary_key"` | |
Username string | |
Password string | |
} | |
func init() { | |
db, _ = gorm.Open("mysql", "root:@tcp(localhost:3306)/test?charset=utf8mb4&parseTime=true&loc=Local") | |
db.SingularTable(true) | |
db.LogMode(true) | |
} | |
// CreateUser . | |
func CreateUser(db *gorm.DB, user User) error { | |
err := DoInTransaction(db, func(tx *gorm.DB) error { | |
return tx.Create(&user).Error | |
}) | |
return err | |
} | |
// CreateUserWithError . | |
func CreateUserWithError(db *gorm.DB, user User) error { | |
err := DoInTransaction(db, func(tx *gorm.DB) error { | |
return errors.New("create user failed") | |
}) | |
return err | |
} | |
func main() { | |
user := User{Username: "foo", Password: "bar"} | |
_ = CreateUser(db, user) | |
err := CreateUserWithError(db, user) | |
if err != nil { | |
fmt.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Totally neat.