DEV Community

Cover image for Go 1.28 will flag the error your rows.Next() loop forgets
Jules Robineau
Jules Robineau

Posted on Originally published at jrobineau.com

Go 1.28 will flag the error your rows.Next() loop forgets

A for rows.Next() loop that stops early looks like a shorter result. Without rows.Err(), your service returns a truncated list with a 200. Go 1.28 adds a vet analyzer for that mistake. I ran it on a dozen of my Go services. It found nothing, and that is exactly the problem.

TL;DR: the Go 1.28 release notes, still a draft, announce two vet analyzers: scannererr for bufio.Scanner and sqlrowserr for database/sql. Both already exist in golang.org/x/tools. On a dozen of my Go services, sqlrowserr reported zero cases. Not because the code is clean: because it reads Postgres through pgx, and the analyzer only looks at database/sql. A manual grep found four rows.Next() without rows.Err(), one of them in production.

Source status: snapshot as of November 3, 2026. The Go 1.28 notes are a draft. The analyzers may change before the release expected in February 2027.

This article is for Go developers who read SQL results or streams line by line.

A loop that stops early looks like a shorter result

Here is the database/sql contract. rows.Next() returns true when a row is ready. It returns false when there are no more rows. It also returns false when an error happens during the read.

The documentation says it word for word: "Rows.Err should be consulted to distinguish between the two cases." Without that call, the two cases blur. A connection cut after row 40 of a 200-row result gives a list of 40 items. And err is nil.

Your HTTP handler then returns a 200 with 40 rows. The client sees nothing wrong. Neither do your tests, because they run against a local database that never drops. It is the same family of failure as the green test suite on a broken product: success and failure look alike. Go has others, such as January 31 plus one month giving March 3, with no error.

The damage depends on the loop. A truncated list in a web page is a quiet bug. A partial sum in a billing calculation is lost money. An incomplete security export is a hole in your audit. In my MFA article, the export handler calls rows.Err() for that reason.

bufio.Scanner has the same flaw. sc.Scan() returns false at the end of the file, and also on a read error. A line too long for the buffer stops the loop without a sound. Only sc.Err() tells the difference.

Go 1.28 adds two vet analyzers for this mistake

go vet is the static analyzer that ships with Go. The Go 1.28 release notes add two analyzers to it. I quote the draft as is:

The new scannererr analyzer checks for failure to handle scanner errors after a loop around bufio.Scanner.Scan, which may cause scanning or I/O errors to go unreported. The sqlrowserr analyzer performs a similar check for loops around sql.Rows.Next, so that iteration errors are correctly distinguished from a smaller result.

The page is labeled "DRAFT RELEASE NOTES". It states: "Go 1.28 is expected to be released in February 2027." Nothing is final. An analyzer can still change its name, its rule, or disappear.

I read the code of both analyzers in golang.org/x/tools. The sqlrowserr rule is simple. It looks for a call to Query or QueryContext on a sql.DB, sql.Conn, sql.Tx or sql.Stmt. The result must land in a local variable. That variable must be used in a loop that calls Next. If Err is never called on it, the analyzer reports.

It stays silent as soon as the variable leaves the function: passed as an argument, returned, stored in a field. The package documentation owns that choice: the goal is to catch the simple oversight, not to guarantee all error handling. To silence a deliberate case, _ = rows.Err() is enough.

scannererr follows the same logic for bufio.NewScanner. It ignores scanners built on a strings.Reader or a bytes.Buffer, because an in-memory read does not fail.

My lab: a dozen Go services, zero reports

One of my projects has a dozen Go services. They declare go 1.25.0 and all read Postgres through pgx, mostly through code generated by sqlc. I compiled the two analyzers into a small binary, then ran go vet -vettool on each module.

Result: zero reports, across the twelve modules, for both analyzers. One test package in one module did not compile, because a fake gRPC client was one method behind. The analyzer skipped it. Everything else was analyzed.

I would have liked to write that my code is clean. The real reason is elsewhere. None of these modules imports database/sql. The pgx.Rows type is a pgx interface, not the standard library's *sql.Rows. And the analyzer only looks at seven methods, all in database/sql.

To be sure, I wrote the same loop twice in a test module. One version with db.QueryContext from database/sql, one with pool.Query from pgx. Neither calls rows.Err(). The analyzer reports the first one:

std.go:10:15: sql.Rows "rows" is used in Next loop at line 16 without final check of rows.Err()
Enter fullscreen mode Exit fullscreen mode

It says nothing about the second. So zero reports on my services means zero coverage, not zero bugs. The project's only bufio.NewScanner, in a test, does call scanner.Err(). There, the silence is deserved.

sqlrowserr looks at database/sql, my code uses pgx

Zero reports means zero coverage, not zero bugs. The analyzer only looks at database/sql. My services read Postgres through pgx, and the grep finds four gaps there.

What the analyzer cannot see, I looked for by hand

I counted with grep. The twelve modules contain 118 calls to rows.Next() and 114 to rows.Err(). The code generated by sqlc always calls rows.Err() after the loop. The four gaps are in hand-written code.

Two are in integration tests, one of them reading a single row. A third is in a command that loads users to seed a database: a truncated list seeds fewer users, with no error at all. The fourth is in a production repository. Here is the code, identifiers renamed:

func (r *HistoryRepo) ListByCaseID(ctx context.Context, caseID string) ([]domain.Event, error) {
    rows, err := r.pool.Query(ctx,
        `SELECT id, event_type, title, created_at
         FROM case_events WHERE case_id = $1 ORDER BY created_at ASC`, caseID)
    if err != nil {
        return nil, fmt.Errorf("list events: %w", err)
    }
    defer rows.Close()

    var events []domain.Event
    for rows.Next() {
        var e domain.Event
        if err := rows.Scan(&e.ID, &e.EventType, &e.Title, &e.CreatedAt); err != nil {
            return nil, fmt.Errorf("scan event: %w", err)
        }
        events = append(events, e)
    }
    if events == nil {
        events = []domain.Event{}
    }
    return events, nil // rows.Err() is never read
}
Enter fullscreen mode Exit fullscreen mode

This function returns the history of a case. If the connection drops halfway, it returns the first events and nil. The calling service builds the case view with a shortened history. The user sees a normal page, just shorter. No log, no alert.

This code is in one of my repositories anyway. It is exactly the oversight an analyzer should catch. And the pgx documentation is as clear as the standard library's. It says: "Callers should check rows.Err() after rows.Next() returns false to detect whether result-set reading ended prematurely due to an error."

The fix is three lines

For database/sql, add the check right after the loop:

for rows.Next() {
    // ...
}
if err := rows.Err(); err != nil {
    return nil, err
}
return ids, nil
Enter fullscreen mode Exit fullscreen mode

For pgx, the same three lines work. pgx also offers helpers that do the check for you. pgx.CollectRows and pgx.ForEachRow call rows.Err() at the end of the loop, I checked their source. With db tags on the struct, the function above becomes:

rows, err := r.pool.Query(ctx, query, caseID)
if err != nil {
    return nil, fmt.Errorf("list events: %w", err)
}
events, err := pgx.CollectRows(rows, pgx.RowToStructByName[domain.Event])
if err != nil {
    return nil, fmt.Errorf("list events: %w", err)
}
return events, nil
Enter fullscreen mode Exit fullscreen mode

For bufio.Scanner, it is if err := sc.Err(); err != nil after the loop. If you know the read cannot fail, write _ = sc.Err() with a comment. The analyzer goes quiet, and the reviewer understands it is a choice.

A test that fails when the loop stops early

An analyzer catches the oversight in the code. A test proves the consequence. With database/sql, the go-sqlmock library can simulate an error in the middle of the result with RowError. Here is the table test I ran on my two versions of the function:

func TestListIDs_StopsEarly(t *testing.T) {
    tests := []struct {
        name    string
        fn      func(context.Context, *sql.DB) ([]int64, error)
        wantErr bool
    }{
        {"buggy", listIDsBuggy, true},
        {"fixed", listIDs, true},
    }
    for _, tc := range tests {
        t.Run(tc.name, func(t *testing.T) {
            db, mock, err := sqlmock.New()
            if err != nil {
                t.Fatal(err)
            }
            defer db.Close()
            rows := sqlmock.NewRows([]string{"id"}).
                AddRow(int64(1)).AddRow(int64(2)).AddRow(int64(3)).
                RowError(1, errors.New("connection reset"))
            mock.ExpectQuery("SELECT id FROM things").WillReturnRows(rows)

            ids, err := tc.fn(context.Background(), db)
            if tc.wantErr && err == nil {
                t.Fatalf("got %d ids and no error, want an error", len(ids))
            }
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

The version without rows.Err() fails with the message got 1 ids and no error, want an error. Three rows in the result, one returned, no error. The fixed version passes.

With pgx, there is no official mock. Write a fake pgx.Rows whose Next returns false after one row and whose Err returns an error. The test must demand an error, not a list. In this lab, I only tested the database/sql version.

Run the analyzers today, without waiting for Go 1.28

Both analyzers are already in golang.org/x/tools v0.52.0. They have no ready-made command: the package's main.go carries a //go:build ignore. So you need a three-file module:

mkdir vet128 && cd vet128
go mod init vet128
cat > main.go <<'EOF'
package main

import (
    "golang.org/x/tools/go/analysis/multichecker"
    "golang.org/x/tools/go/analysis/passes/scannererr"
    "golang.org/x/tools/go/analysis/passes/sqlrowserr"
)

func main() {
    multichecker.Main(scannererr.Analyzer, sqlrowserr.Analyzer)
}
EOF
go mod tidy
go build -o vet128 .
Enter fullscreen mode Exit fullscreen mode

Then, in each module to check:

go vet -vettool=/path/to/vet128 ./...
Enter fullscreen mode Exit fullscreen mode

The binary weighs about 9 MB. It needs Go 1.26 or newer, not Go 1.28. My local go vet, on Go 1.26.3, knows neither analyzer. gopls 0.22 already enables scannererr by default in the editor, but not sqlrowserr.

If you use pgx, add a grep until something better exists:

for f in $(grep -rl 'rows.Next()' --include='*.go' .); do
  n=$(grep -c 'rows.Next()' "$f"); e=$(grep -c 'rows.Err()' "$f")
  [ "$n" -gt "$e" ] && echo "$f next=$n err=$e"
done
Enter fullscreen mode Exit fullscreen mode

It is crude. It compares files, not functions. It still found my four gaps in a few seconds.

The checklist

A rows.Next() loop without rows.Err() cannot tell the end of the result from a failure.

  • [ ] Call rows.Err() after every rows.Next() loop, with database/sql and with pgx alike
  • [ ] Call sc.Err() after every sc.Scan() loop over a file or a network stream
  • [ ] With pgx, prefer pgx.CollectRows or pgx.ForEachRow over hand-written loops
  • [ ] Compile scannererr and sqlrowserr into a multichecker and run it in CI
  • [ ] Know what your analyzer covers: sqlrowserr only sees database/sql
  • [ ] Compare your rows.Next() to your rows.Err() with a grep for non-standard drivers
  • [ ] Write a test where the read fails halfway and demand an error
  • [ ] Re-read the Go 1.28 notes at release time: the draft can change

The takeaway

An iteration error looks like a smaller result. That is the sentence from the Go 1.28 notes, and it is the whole point. The analyzer is coming, but it only covers database/sql. If you are on pgx, your tools are still code review and a grep.

Run the binary on your code this week. Then count your rows.Next() against your rows.Err(). The gap is your list of silent bugs.

Want a review of your database access code and your Go CI? See my Go backend takeover offer, or let's talk.


Sources: Go 1.28 release notes (draft) · sqlrowserr analyzer · scannererr analyzer · database/sql, Rows.Next and Rows.Err · bufio, Scanner.Err · pgx v5, Rows interface and CollectRows · multichecker package · go vet documentation · go-sqlmock, RowError

Top comments (0)