Help me understand the transaction example #2031
Replies: 2 comments 1 reply
-
I don't have an answer I'm afraid. I just wanted to say that you helped me understand why I was struggling with finding a clean solution to transactions. Now I understand that I just have to keep passing around a concrete database instance. I was convinced that that wasn't the case, but now that you've helped me understand, I can accept it and move on. I think if I at least understood why it's like this, then I might not have spent so much fighting it. |
Beta Was this translation helpful? Give feedback.
-
Hey @preslavrachev - I just ignore the WithTx method, actually. When I initialize the queries struct, I use the |
Beta Was this translation helpful? Give feedback.
-
Looking at the generated code,
Queries
has adb
attribute, which is essentially a reference to the database. In order to instantiateQueries
, one needs to supply it with a concretedb
instance. So far, so good.The issue comes with transactions. To work with transactions, I need to create a new instance of
Queries
callingWithTx()
. The problem is that the function now wants me to pass a transaction instance to it, coming from a concretedb
instance:In my view, this breaks the basic principle of encapsulation. One of the reasons, I am going to pass a
Queries
instance around, and not a*sql.DB
is to prevent it from from accessing the database directly. However, this piece of code wants me to do just that - pass a concrete instance around.The only workaround I see at this point in time is wrapping
Queries
in a struct local to my code, which will also keep a reference to the DB and expose a Method for generating a transaction-capable instance.Does anyone have a better suggestion?
Beta Was this translation helpful? Give feedback.
All reactions