If you have any questions or feedback, pleasefill out this form
Table of Contents
This post is translated by ChatGPT and originally written in Mandarin, so there may be some inaccuracies or mistakes.
I researched some of the currently popular sql
packages and found that almost none of them have a feature that throws an error immediately when a connection is lost. For example, in nodejs
with MySQL, we can listen for errors using connection.on('error')
.
However, in Golang (at least in several popular packages), there isn't a similar feature available. Upon further investigation, it's not hard to understand why.
The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has a concept of per-connection state, such state can be reliably observed within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the returned Tx is bound to a single connection. Once Commit or Rollback is called on the transaction, that transaction's connection is returned to DB's idle connection pool. The pool size can be controlled with SetMaxIdleConns.
In simple terms, when you call sql.Open
, it does not actually establish a connection; instead, it maintains a connection pool internally and only attempts to connect when necessary. This means that if you lose a connection due to network issues while executing a query, database/sql
will attempt to retry for you at the lower level.
On the bright side, this is a good thing, as it saves you from having to handle the retry logic yourself. However, sometimes you might prefer to be aware of a lost connection before executing a query, so that the entire application knows about the issue in advance.
If you want to achieve similar functionality, you will need to rewrite the underlying Dialer logic to ensure that your application is notified immediately when a network disconnection occurs.
If you found this article helpful, please consider buying me a coffee ☕ It'll make my ordinary day shine ✨
☕Buy me a coffee