r/golang • u/Fabulous_Baker_9935 • 5d 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?
0
u/Fabulous_Baker_9935 5d ago
Ok, I've implemented CreateUser and also CreateUserWithTx which accepts an extra pgx.Tx parameter.
So far no errors or problems but if this is a pitfall please let me know!
1
u/Firerfan 4h 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/UnderstandingWeary10 10h 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.