Skip to content

Instantly share code, notes, and snippets.

@mkfeuhrer
Created March 18, 2020 18:20

Revisions

  1. mkfeuhrer created this gist Mar 18, 2020.
    32 changes: 32 additions & 0 deletions transaction_postgres_gorm.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    // 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()