Skip to content

Instantly share code, notes, and snippets.

@mkfeuhrer
Created March 18, 2020 18:20
Show Gist options
  • Save mkfeuhrer/1294dfe4186695faafaf09fe0ed7ba02 to your computer and use it in GitHub Desktop.
Save mkfeuhrer/1294dfe4186695faafaf09fe0ed7ba02 to your computer and use it in GitHub Desktop.
// 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