walterwanderley/sqlc-grpc is a very interesting project that builds on the output of kyleconroy/sqlc to generate a functional REST/JSON and GRPC server. When I started toying with it, I was a little disappointed that I couldn’t easily add any application logic outside of my SQL. This could be great for scaffolding a project, but then it seemed like I might not be able to add anything like validation.
Having had some more time to explore the project, now, I see that there is some
way to be able to add a layer between the communication layer and the database
layer. The key is to add an extra agrument to your sqlc configuration file:
emit_interface
.
version: "1"
packages:
- path: "internal/authors"
queries: "./sql/queries.sql"
schema: "./sql/migrations/"
engine: "sqlite"
emit_interface: true
When you generate code with sqlc-grpc
with this argument, the authors package
now gets a new file querier.go
, which contains the interface representing the
queries that kyleconroy/sqlc generated. The package’s sservice.factory.go
file is an editable file. What this enables for us is to implement the
interface defined in querier.go
, which can wrap calls to the Querier
generated by kyleconroy/sqlc, and add application logic.
That’s too many words with maybe not enough structure, so I created a demo repository.