Common interface for query functions in sql.DB and sql.Tx

Chunting Wu
2 min readOct 1, 2021

--

I want to implement a command pattern upon the database/sql in golang. The goal is that no matter whether the client uses sql.DB or sql.Tx, it can get the result by executing the same command. So that, the client can decide which instance to pass the command according to its needs. The problem is golang is a strongly typed language; therefore, you have to define the instance type in command’s struct first. They are two different types(sql.DB and sql.Tx), and it bothers me.

There is an interesting discussion on Github of the golang standard library. I am looking for the same solution like the issue author’s proposal; thus, I read the whole posts in the discussion.

I extract two important points:

  1. Many people have the same requirement, so the issue is more like a common abstraction to the high-level design. Libraries are used to ease up things and to not make everyone repeat the very same work.
  2. Does such an interface need to live in the standard library? It is more like a design concept than a driver.

Originally, my thoughts were biased towards the former and then I felt that the latter was more correct. From my point of view, the common platform cannot meet everyone’s design concept, that is not practical. If there is indeed a design need, which means it have to be accomplished by a new high-level library. In this case, sqlexp has already played this role. We can either buy in it or create another one.

--

--

Chunting Wu
Chunting Wu

Written by Chunting Wu

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

Responses (1)