Can not implement transaction

I’m trying to implement transaction but something went wrong.
By my business logic there should be an error on second user from list and transaction should not be completed but it actually completed for some reason…

func closeTransaction(tx *sql.Tx, commit *bool) {
	if *commit {
		log.Info("Commit sql transaction")
		if err := tx.Commit(); err != nil {
			log.Warning(err)
		}
	} else {
		log.Warning("Rollback sql transcation")
		if err := tx.Rollback(); err != nil {
			log.Warning(err)
		}
	}
}

	...
	tx, _ := db.Begin()
	commitTx := false
	defer closeTransaction(tx, &commitTx)
	log.Info("Begin sql transaction")

	for _, user := range userlist {
		// here I impletemented logic where on second **user** from **userlist** there
		// will be an error i.e. trx should NOT be completed
		// but for some reason it completed when I check database records...
		...
		if err != nil {
			log.Warning(err)
			http.Error(w, "Unable to persist user - wrong user data", 405)
			return 
			// should be failure i.e. full trx is NOT completed
			// but for some reaosn it persisted first user 
		}
	}

	commitTx = true
	return // should be success i.e. full trx is completed

What’s wrong with this code? By the way, I use db.Exec(sqlStatement, …) to write database - is it related somehow to the issue?

2 Likes

solution: the issue was caused by using db.Exec instead of tx.Prepare and then stmt.Exec

2 Likes

Hi, @cinematik, can you flag this issue as solved?

2 Likes

Hi, @skillian, I’ve flaged it as solved.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.