Sqlx Transactions

Hello,

I am using sqlx to insert multiple rows to mysql database tables which have foreign key releations. Could you please review the code below? I am not sure where to use rollbacks. Is this a good practice ?

tx, err := db.Begin()
if err != nil {
	return
}

r, err := tx.Exec("INSERT INTO licenses ...")
if err != nil {
	tx.Rollback() //shoul i use rollback here ? 
	return
}
licenseId, _ := r.LastInsertId()

r, err = tx.Exec("INSERT INTO companies ...", licenseId, ...)
if err != nil {
	tx.Rollback()
	return
}
companyId, _ := r.LastInsertId()

r, err = tx.Exec("INSERT INTO users ...", companyId, ...)
if err != nil {
	tx.Rollback()
	return
}

err = tx.Commit()
if err != nil {
	tx.Rollback() //shoul i use rollback here ? 
	return
}

Best regards…

If the three INSERT statements must all be successful or none of it must have effect, you have to rollback the transaction at every error, just as you do.

Thank you!

What happen if you have uuid instead of id? because r.LastInsertId() returns an int64.

Hello and welcome,

I don’t know the answer of this question :slight_smile:

Write defer function for commit and roolback