Add mock versions of SQLiteDriver and SQLiteConn for +build !cgo #819
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.
My app can use PostgreSQL and – optionally – SQLite. I would like to be
able to compile the app without cgo when SQLite isn't used, as this
removes the need for a C compiler which makes builds easier and faster,
especially for end-users.
In the simple case, this is not a problem go-sqlite3 already provides a
simple non-cgo mock so it compiles and gives a runtime error if you try
to use it anyway.
However, now I'd like to register a function for my SQLite connection to
match a PostgreSQL function like so:
But this makes it quite hard to keep the same logic since it refers to
types that don't exist with CGO_ENABLED=0. I will need to create a db.go
with
+build !cgo
and db_cgo.go with+buid cgo
which duplicates allthe logic but with the sqlite hooks. In my case, this actually affects
quite a lot; for example I have a helper function which connects and
runs migrations and whatnot which looks like:
And I'd have to have two versions of that, too. You could perhaps do
something with interfaces, but because the sql.Register() call above
references the
sqlite3.SQLiteDriver.ConnectHook
struct field that'snot so straightforward (and wrapping stuff in interfaces probably won't
do much for the general clarity either).
This simplifies all of that by providing some common types that may be
used when setting up a SQLite connectin. I renamed the
SQLiteDriverMock
to&SQLiteDriver
for this reason. As far as I cantell in my testing, this has no real downsides (but perhaps I missed
something?)
Note: it might also be worth doing something similar for error.go, as I
already have two variants of the below function (one with cgo as below,
and one without cgo which checks just PostgreSQL):
This is a lot more manageable than the ConnectHook case, but it would be
nicer if it would work without the need for build tags.