In this post, I will share my notes on handling SQL queries in GoLang, especially complex queries. This is a work in progress, so I will continue to update my notes here.
A bit of background: I recently wrote a few straightforward microservices, such as user management, notifications, and comments, which require interaction with a PostgreSQL database for CRUD operations.
While this approach works initially, diving deeper into the code reveals raw SQL queries. This might be acceptable for now, but as requirements expand, it becomes problematic for developers to write increasingly complex and repetitive code. For example:
- Query to get a user by ID
- Query to get a user by email
- Query to get a user by zip-code
- Query to get users by creation date
- Query to get users by password expiration date
Refer: https://studygolang.com/resources/14744
To address this issue, the first step is to search GitHub for an ORM similar to Gorilla Mux in routing. If you have experience with Python Django or Java, you might be tempted to find something similar.
I have already explored many GitHub repositories but haven’t been convinced by the solutions offered. Many repositories provide SQL query builders, which I am still analyzing. Since I am working on a critical project, I might create my own SQL query builder and map query results to models.
In the meantime, I found this insightful post: https://andrewpillar.com/programming/2019/07/13/orms-and-query-building-in-go/
References:
- Jet is the easiest and fastest way to write complex, type-safe SQL queries as Go code and map database query results into complex object compositions. It is not an ORM. https://github.com/go-jet/jet
- https://github.com/andrewpillar/query/blob/master/query.go
- https://github.com/jmoiron/sqlx
- https://github.com/gchaincl/dotsql