Skip to content
New issue

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

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

Already on GitHub? # to your account

feat(docs): how-to use transactions with pgx #3557

Merged
merged 1 commit into from
Aug 23, 2024
Merged

feat(docs): how-to use transactions with pgx #3557

merged 1 commit into from
Aug 23, 2024

Conversation

pedro-tiple
Copy link
Contributor

Update the documentation as described in issue #3192.

@kyleconroy kyleconroy merged commit a353d74 into sqlc-dev:main Aug 23, 2024
8 checks passed
@pedro-tiple pedro-tiple deleted the 3192_update-howto-transactions-pgx branch August 23, 2024 16:53
@fr11nik
Copy link

fr11nik commented Jan 21, 2025

I prefer to create into db package ReadCommited function that start transaction

// any sqlc function
type Handler func(*Queries) error

func (store *SQLStore) ReadCommited(ctx context.Context, fn Handler) error {
	tx, err := store.db.Begin(ctx)
	if err != nil {
		return err
	}
	defer func() {
		rbErr := tx.Rollback(ctx)
		if rbErr != nil {
			// Log the rollback error
			log.Printf("rollback error: %v", rbErr)
		}
	}()
	err = fn(store.WithTx(tx))
	if err != nil {
		// Return the original error along with the rollback error if any
		return fmt.Errorf("transaction error: %v", err)
	}

	return tx.Commit(ctx)
}

And use into store.go

type Store interface {
	Querier
	ReadCommited(ctx context.Context, fn Handler) error
}

Use it via

func bumpCounter(ctx context.Context,store tutorial.Store, id int32) error {
  err := store.ReadCommited(ctx,func(qtx *tutorial.Queries) error {
    r, err := qtx.GetRecord(ctx, id)
    if err != nil {
      return err
    }
    return qtx.UpdateRecord(ctx,tutorial.UpdateRecordParams{
      ID:      r.ID,
      Counter: r.Counter + 1,
    })
  })
  return err
}

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants