Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transactions Usage #396

Closed
sachnk opened this issue Sep 26, 2018 · 1 comment
Closed

Transactions Usage #396

sachnk opened this issue Sep 26, 2018 · 1 comment

Comments

@sachnk
Copy link

sachnk commented Sep 26, 2018

Hi,

I'm trying to use transactions with sqlboiler with psql and I want to confirm my usage of Rollback() and Confirm()

For example, if I begin a transaction and I detect an error and want to abort the transaction, should I call Rollback()? Or is it sufficient to simply not call Commit()?

tx, _ := db.BeginTx(...)

// on error, abort the transaction
if some_error {
  tx.Rollback() // <-- do we need to rollback, or can we just return out?
  return
}

// no error, commit the transaction
tx.Commit()
@aarondl
Copy link
Member

aarondl commented Sep 30, 2018

You always need to explicitly rollback or commit a transaction (this isn't really a part of sqlboiler fwiw). The way I handle this in a program is with a helper:

func Tx(ctx context.Context, db *sql.DB, fn func(tx *sql.Tx) error) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}

	err = fn(tx)
	if err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit()
}

Then you call it like this:

helpers.Tx(ctx, db, true, func (tx *sql.Tx) error {
   err := // do something databasey
   if err != nil {
     return err // The helper will automatically rollback for you here
   }

   return nil // The helper will automatically call commit since you returned nil
})

@aarondl aarondl closed this as completed Sep 30, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants