Add DBTX Param config option #1279
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
I'd like to be able to define a type that wraps a small interface along the lines of
Using
sqlcto generate the underlying code today would give a*Queriesthat has these two relevant methods:Because
*Queriesoperates against an internalDBTX, to useInsertWidgetagainst a pre-existing transaction then requires creating a new*Queriesby use of itsWithTxmethod. But becauseWithTxreturns*Queries, it's non-trivial to keep this as just an implementation detail—to have an interface that doesn't expose the underlying*Queriesrequires either:WithTxthat return the desired interface (which also requires now that the interface be accessible to the generated package, instead of being defined potentially only at the consumer site), orQuerierinstead of just one of its methods)Some of the why for both of these is covered in #383 and golang/go#7512.
Proposal
Support a new configuration parameter
dbtx_paramthat modifies the generated method sets to provide methods like shown inWidgetInserter. If set totrue, the generated*Queriesomits storing a DBTX as a struct field and requires it be passed in to all method calls. In doing so, it allows callers to easily provide the connection for standalone use or for use as part of a broader transaction and makes it easy for the surrounding code to use a narrowly defined interface.Notes
This PR's current implementation treats
emit_prepared_queriesanddbtx_paramas mutually exclusive config options. The thought being that since prepared queries are prepared against a particular database connection, and because executing the queries would now use a caller-provided connection, these two connections may end up distinct and void the value of preparing the queries. The implementation can be changed to support two the config options together, it'd just be more involved to do so.