Created
March 18, 2020 18:20
-
-
Save mkfeuhrer/1294dfe4186695faafaf09fe0ed7ba02 to your computer and use it in GitHub Desktop.
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
// Here - db is package name for Postgres Gorm db setup | |
// Begin Transaction | |
txn, err1 := db.Begin() | |
if err1 != nil { | |
return err1 | |
} | |
defer func() { | |
// Rollback in case of Failure | |
// Note - within a transaction don't use db, use txn only. | |
if r := recover(); r != nil { | |
txn.Rollback() | |
} | |
}() | |
// Execute | |
sqlStatement := `select * from users where id=?;` | |
txn.DB().Exec(sqlStatement, 1) | |
err := txn.DB().Error | |
if err != nil { | |
txn.Rollback() | |
return err | |
} | |
// Commit | |
err1 = txn.Commit() | |
if err1 != nil { | |
log.Fatal(err1) // also txn.Rollback? | |
} | |
// Close | |
txn.Close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment