Using a query builder
Sometimes, writing SQL can be complicated, especially when you are building your query based on some conditions. For example, if you only want to apply particular filtering if the user sets an option, you must create the query using concatenation or string interpolation. I prefer to use a query builder. It makes my code more explicit and more manageable.
Let’s see an example of this in action:
func (r *Repository) GetUsers(includeDeleted bool) ([]User, error) {
query := sq.Select("*").From("users")
if !includeDeleted {
query = query.Where(sq.Eq{"deletedAt": 0})
}
...
}
As you can see in the code, a specific part of the query is only included when needed. Also, the query is built using a fluent interface that makes it easy to read and understand.
Another option would be an ORM, but I prefer SQL builders because they give me more control over the executed SQL.
In this book, we will use SQuirreL...