2

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.

4
  • You accepting point in the function funcThatDoesSomethingWithRows but you not passing reference to it when calling go funcThatDoesSomethingWithRows(rows) it should be address of rows funcThatDoesSomethingWithRows(&rows) Commented Feb 8, 2023 at 15:45
  • 2
    I would call it a bad practice simply because the row closing operation is not visually paired with the acquisition operation, which is WTF for the readers. Commented Feb 8, 2023 at 15:45
  • Or lint can ignore by passing comment //nolint Commented Feb 8, 2023 at 15:47
  • 1
    Based on the code you've presented, it's impossible to tell if it's even correct. I can't tell when/if funcThatDoesSomethingWithRows() is always called, to know if it's handling closing in all cases. I'm also not sure why you'd want to do that in a goroutine. Commented Feb 8, 2023 at 16:16

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.