golangci-lint complains on SQL rows not closed, despite it is closed from a goroutine

596 Views Asked by At

I am using golangci-lint as part of my CI/CD. It is complaining on SQL rows not being closed, despite it is being closed from a goroutine:

....
    rows, err := ...
    ...
    go funcThatDoesSomethingWithRows(rows)
}
...
func funcThatDoesSomethingWithRows(rows *sql.Rows) {
    defer rows.Close()

The message I am getting is

Rows/Stmt was not closed (sqlclosecheck)

Is that really a bad pattern and I should avoid doing it, or a bug with golangci-lint? How can I make golangci-lint ignore that?

EDIT:

I left out an important piece from my sample code. Here is an update:

....
    rows, err := ...
    if err != nil {
         return ....
    }
    ...
    go funcThatDoesSomethingWithRows(rows)
}
...
func funcThatDoesSomethingWithRows(rows *sql.Rows) {
    defer rows.Close()

So the problem is that in case of an error before starting the goroutine, Close will never be called. So I had to explicitly call it, in case of an error.

1

There are 1 best solutions below

0
On

Analysing your code, seems like this might cause a problem.

If my understanding is correct, your code will return if your err is not nil. Then row will not be closed since it will not reach the funcThatDoesSomethingWithRows