Can not implement transaction

(Andre) #1

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 {
	} else {
		log.Warning("Rollback sql transcation")
		if err := tx.Rollback(); err != nil {

	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 {
			http.Error(w, "Unable to persist user - wrong user data", 405)
			// 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?

(Andre) #2

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

(Sean Killian) #3

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

(Andre) #4

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

(system) closed #5

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