errcheck icon indicating copy to clipboard operation
errcheck copied to clipboard

Feature Request: When using database/sql's Rows type, rows.Err() must be called

Open nchelluri opened this issue 5 years ago • 1 comments

I have a feature request: It would be nice if the linter saw that I forgot to respect the protocol of the Rows struct and didn't call rows.Err() to check if there was an error during iteration through the SQL rows.

Please see this attached sample program:

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/lib/pq"
	"log"
)

func main() {
	connStr := "host=localhost user=test password=test dbname=test sslmode=disable"
	db, err := sql.Open("postgres", connStr)
	if err != nil {
		log.Fatal(err)
	}

	rows, err := db.Query("SELECT usename FROM pg_catalog.pg_user")
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
	      if err := rows.Close(); err != nil {
	      	 log.Fatal(err)
	      }
	}()
	for rows.Next() {
		var usename string
		if err := rows.Scan(&usename); err != nil {
			log.Fatal(err)
		}
		fmt.Println(usename)
	}
}

If I run errcheck on it, I don't see any errors:

vagrant@ct100-test:~/dev/errcheck/sqlrowserr $ errcheck sqlrowserr.go
vagrant@ct100-test:~/dev/errcheck/sqlrowserr $ 

However, you can see that I forgot to check rows.Err(). It would be really nice if this linter caught that problem.

Thanks!

nchelluri avatar Sep 12 '19 12:09 nchelluri

there're other linters like https://github.com/jingyugao/rowserrcheck, https://github.com/ryanrolds/sqlclosecheck, maybe you could take a look.

lance6716 avatar Jun 24 '21 07:06 lance6716