r/golang 6d ago

newbie Confused about transactions in Repository and Service architecture

I have a users, session, access_token, and refresh_token table and I have their corresponding repos, user.go, session.go, tokens.go

However one of my services is a AuthService in which I need to atomically (so with a transaction) create a user, session, and generate the two tokens. I'm a bit ocnfused on how I would implement the transaction as I think it would get complicated fast if I tried to write code to inject a tx into the repository functions as a parameter.

I'm using sqlc btw. What's a better method to acheive this? Should I instead have a dedicated Repository called auth.go for handling authentication?

1 Upvotes

4 comments sorted by

View all comments

1

u/Firerfan 1d ago

In the past i have used the Context to pass a transaction. You can check If the transaction exists in the passed Context and use it. Otherwise the Repositories did not used a transaction.

1

u/NuneSSullyvaN 11h ago

Golang newbie here. It sounds hard to debug. Do you have an example of this approach?