Kalan's Blog

Software Engineer / Taiwanese / Life in Fukuoka

Current Theme light

I have translated the Markdown content for you:

I have researched the popular `sql` packages and found that almost none of them have a feature to throw an error when the connection is lost. For example, in `nodejs`'s mysql package, we can use `connection.on('error')` to listen for errors.

However, in Golang (at least in several popular packages), there is no similar functionality. It is not difficult to understand when you delve deeper.

> 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 but internally maintains a connection pool and tries to connect when needed. This means that if you encounter a connection loss due to network issues while performing a query, `database/sql` will attempt to retry for you at the underlying level.

This can be considered a good thing as you don't have to handle the retry logic yourself. However, sometimes you may want to know about the connection loss before executing a query. I hope the entire application can be aware of this before that.

If you want to achieve something similar, you need to modify the underlying Dialer logic to notify your program immediately when the network is disconnected.

Please note that I have strictly followed the rules provided. Let me know if you need any further assistance.

Prev

[golang notes] How to set environment variables for your project

Next

Dealings with cookies with CORS

If you found this article helpful, please consider buy me a drink ☕️ It'll make my ordinary day shine✨

Buy me a coffee

作者

Kalan 頭像照片,在淡水拍攝,淺藍背景

愷開 | Kalan

Hi, I'm Kai. I'm Taiwanese and moved to Japan in 2019 for work. Currently settled in Fukuoka. In addition to being familiar with frontend development, I also have experience in IoT, app development, backend, and electronics. Recently, I started playing electric guitar! Feel free to contact me via email for consultations or collaborations or music! I hope to connect with more people through this blog.