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
sqlc
to generate the underlying code today would give a*Queries
that has these two relevant methods:Because
*Queries
operates against an internalDBTX
, to useInsertWidget
against a pre-existing transaction then requires creating a new*Queries
by use of itsWithTx
method. But becauseWithTx
returns*Queries
, it's non-trivial to keep this as just an implementation detail—to have an interface that doesn't expose the underlying*Queries
requires either:WithTx
that 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), orQuerier
instead 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_param
that modifies the generated method sets to provide methods like shown inWidgetInserter
. If set totrue
, the generated*Queries
omits 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_queries
anddbtx_param
as 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.