Make SQL Scan result be map in golang

Chunting Wu
2 min readSep 28, 2021

--

When we are using MySQL in golang, we usually adopt database/sql to finish our jobs. In my opinion, the most common driver must be go-sql-driver. It is efficient and easy to use but hard to use well.

Especially, the fetch result sets coming from SELECT are not a slice like other dynamic programming languages. In other dynamic language, we expect the results would be a list to represent what columns you want. Moreover, In Python, we can directly fetch the database and get a dict as a result set.

In golang, we have to define the variables first, and then manually assign those variables to Scan. This implementation results in 2 problems:

  1. If we issued a SELECT *, we will encounter an error if the schema changes in the future.
  2. If we want to ask for a new column, we have to aware where uses the result sets. And modify them all carefully although they didn’t care the new column.

To sum up, we need a method to mitigate those common problems after all. My idea comes from Python, I want the result sets to be a map, so that the caller will not be impacted if any change on the database.

The solution is as follows:

--

--

Chunting Wu
Chunting Wu

Written by Chunting Wu

Architect at SHOPLINE. Experienced in system design, backend development, and data engineering.

No responses yet