Go-sql-driver context cancel not effective in TiDB

This topic has been translated from a Chinese forum by GPT and might contain errors.

Original topic: go-sql-driver context cancel tidb不生效

| username: lazzyfu

Hello everyone~
TiDB version: v5.x
Problem description:
When I use go-sql-driver to access TiDB, the corresponding session in TiDB cannot be canceled after the context ends, but this issue does not occur with MySQL.
The code is as follows:

# 10s timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

# Execute query
rows, err := db.QueryContext(ctx,"select sleep(600)")

After 10 seconds, the timeout is triggered, and the code returns as expected, as follows:

context deadline exceeded

However, when logging into TiDB at this time, I find that the query has not ended in TiDB.

Could you please help me see how to solve this? I don’t want to kill it every time. Or is there any parameter that can be passed?

| username: Billmay表妹 | Original post link

The issue you are facing seems to be related to the implementation of go-sql-driver/mysql. According to the documentation, when using go-sql-driver/mysql, you need to write error handling logic, manually close *sql.Rows, and cannot easily reuse code, which makes your code slightly redundant.

However, the documentation does not mention the issue of context cancellation not working in TiDB. When using TiDB, there may be bugs or limitations in the implementation of go-sql-driver/mysql that cause context cancellation not to work.

Try using Golang’s recommended ORM library GORM instead of go-sql-driver/mysql. The documentation provides instructions on how to use GORM in TiDB transactions.

| username: TiDBer_rvITcue9 | Original post link

Check-in, check-in.