ryanrolds / sqlclosecheck

Linter that confirms DB rows and statements are closed properly.
MIT License
81 stars 14 forks source link

Rows assigned within a conditional fail to trigger "missing close" #11

Open therealplato opened 3 years ago

therealplato commented 3 years ago

Thank you for the tool. Here's a repro of an issue I encountered.

Expected: The linter warns me that I never closed this rows

Actual: Not detected

package sqlx_examples

import (
        "context"
        "database/sql"
        "log"
        "strings"
)

func conditionalRowsMissingClose(onlyAdults bool) {
        age := 21
        var (
                rows *sql.Rows
                err  error
        )
        if onlyAdults {
                rows, err = db.QueryContext(context.Background(), "SELECT name FROM users WHERE age >= ?", age)
        } else {
                rows, err = db.QueryContext(context.Background(), "SELECT name FROM users", age)
        }
        if err != nil {
                log.Fatal(err)
        }
        // defer rows.Close()

        names := make([]string, 0)
        for rows.Next() {
                var name string
                if err := rows.Scan(&name); err != nil {
                        log.Fatal(err)
                }
                names = append(names, name)
        }

        // Check for errors from iterating over rows.
        if err := rows.Err(); err != nil {
                log.Fatal(err)
        }
        log.Printf("%s are at least %d years old", strings.Join(names, ", "), age)
}
ryanrolds commented 10 months ago

Thank you for the test case. I am adding to my list of things to look at. No hard ETA, hoping to have some time of the next couple of weeks.