Skip to content

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
@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
}
alfonsodev pushed a commit to ExponentiaTeam/sqlc that referenced this pull request Oct 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants