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

Add AsyncTransaction #326

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

geekgonecrazy
Copy link

@geekgonecrazy geekgonecrazy commented Nov 7, 2024

Doing a transaction in a callback makes writing go code very cumbersome and maybe a bit javascript like. (which the official mongo go sdk definitely has that feeling). They have a less visible / documented way using session context.

I added a StartAsyncTransaction method to the session that returns a new context that as long as passed in with insert/updates will be associated with the transaction.

Example usage:

	ctx := context.Background()
	cli := initTransactionClient("test")
	defer cli.DropDatabase(ctx)
	session, err := cli.Session()
	if err != nil {
		return err
	}

	sCtx, err := session.StartAsyncTransaction(ctx)
	if err != nil {
		return err
	}

	defer session.EndSession(sCtx)
        defer session.AbortAsyncTransaction(sCtx)

	if _, err := cli.InsertOne(sCtx, bson.D{{"abc", int32(1)}}); err != nil {
		return err
	}

	if err := session.CommitAsyncTransaction(sCtx); err != nil {
		return err
	}

@geekgonecrazy geekgonecrazy marked this pull request as ready for review November 7, 2024 04:52
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

Successfully merging this pull request may close these issues.

1 participant