Cool Features in DBQ (zero boilerplate database operations)

Go is a very verbose language compared to many other popular alternatives. Database queries take numerous lines of code that are often repetitive. The dbq package has some really cool features to write database operations that are straight to the point. Boilerplate code, which is hard on the eyes are now a thing of the past (except when you need absolute raw performance). The icing on the cake is that it works with MySQL and PostgreSQL.

Listed below is the before and after of everyday database tasks:

TASK 1: Insert Multiple Rows into a table

Inserting numerous rows can be error-prone. With dbq, it is as thoughtless as inserting a single row. You can even pass data directly as []string or []int instead of having to convert to []interface{} annoyingly.

Inserting multiple rows

In the example above, the standard code seems more straightforward. But in reality, it is less readable — especially as the number of rows increases. You can also work directly with structured data.

TASK 2: Fetch and Unmarshal all rows from a table

This is where dbq shines. Unmarshaling happens magically via the popular mapstructure package.

Fetching all rows

I think the contrast speaks for itself. The results look something like this for both queries:

([]*main.Row) (len=6 cap=8) {
ID: (int) 1,
Name: (string) (len=5) "Sally",
Age: (int) 12,
CreatedAt: (time.Time) 2019-03-01 00:00:00 +0000 UTC
ID: (int) 2,
Name: (string) (len=5) "Peter",
Age: (int) 15,
CreatedAt: (time.Time) 2019-02-01 00:00:00 +0000 UTC

Other Features

Flatten Query Args

All slices are flattened automatically.

Single Result Fetches

Some queries are going to at most return 1 row. In that case, you can pass the SingleResult option. This will make the Q and MustQ function return a single row (instead of a slice) or nil.

MySQL context cancelation

As you probably already know, context cancelation doesn’t actually cancel the underlying MySQL query. dbq plays nicely with the mysql-go package.


You can see that when you are prototyping and/or trying to get things done, dbq really improves readability and convenience.

You can find the repository here:

Stars and PR’s are always appreciated.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store