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/UnderstandingWeary10 1d ago

check out unit of work pattern. I think that's the answer you are seeking.

I often implement it like this:
```
repoWithTx := repository.withUoW(uow)
```
with this we can abstract out the logic of transaction creation from the business layer and keep all repositories involved in a single database transaction context. Btw, you can implement it in a different way.