Rows of a database query or lines of a scanner are read in a loop whose ending error is never checked

tx0/go:rows-error-uncheckedrecommendedwarningbug

What it finds

for rows.Next() { ... } without rows.Err() afterwards: Next returns false both when the rows are done and when reading them failed, so without asking Err a failure in the middle looks like a complete result. bufio.Scanner works the same way with Scan and Err.

The variable must be local and hold the first result of a method Query or QueryContext with two results in a file that imports database/sql, or the result of bufio.NewScanner. The function must call Next or Scan on it, never Err, and the variable must not leave the function, where someone else could check the error.

From the rule's source, rows_error_unchecked.rs.

Example from the rule's tests
package p import (	"bufio"	"database/sql"	"io") func names(db *sql.DB) ([]string, error) {	rows, err := db.Query("SELECT name FROM users")tx0 reports: rows.Next is looped over but rows.Err() is never checked	if err != nil {		return nil, err	}	defer rows.Close()	var out []string	for rows.Next() {		var name string		_ = rows.Scan(&name)		out = append(out, name)	}	return out, nil} func lines(r io.Reader) []string {	sc := bufio.NewScanner(r)tx0 reports: sc.Scan is looped over but sc.Err() is never checked	var out []string	for sc.Scan() {		out = append(out, sc.Text())	}	return out} func checked(r io.Reader) ([]string, error) {	sc := bufio.NewScanner(r)	var out []string	for sc.Scan() {		out = append(out, sc.Text())	}	return out, sc.Err()}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/go:rows-error-unchecked" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/go:rows-error-unchecked] reason="..."

tx0 explain tx0/go:rows-error-unchecked shows the same in the terminal. Found a false positive? Report it.