Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: cmd/vet: detect defer rows.Close() #34544

Open
zachgersh opened this issue Sep 25, 2019 · 0 comments

Comments

@zachgersh
Copy link

commented Sep 25, 2019

I'd like to suggest, based on the prior art of #17780, that we also add a check to make sure that rows.Close() is always deferred for any SQL call that returns rows). I struggle to think of a false positive especially due to the fact that rows.Close() can be safely deferred in every case.

Consider this code:

        _, err := db.Exec(`INSERT into (age) VALUES (30)`)
        if err != nil {
                return err
        }

Let's say I've done this in some test setup, I'd like to clean up the DB for another set of tests, I am now unable to truncate the database due to the fact that I have left this connection open. Production code won't run into this truncation issue (I hope) but it could potentially put pressure on the database due to the number of open connections instead.

A False positive could potentially look like this:

        rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE age=?", 10)
	if err != nil {
		log.Fatal(err)
	}

	for rows.Next() {
	}

My for loop will have consumed all the rows and I therefore get a close call automatically. We still show a deferred close here for users just in case they decide to break out of their for loop early thus turning this back into a problem.

@gopherbot gopherbot added this to the Proposal milestone Sep 25, 2019
@gopherbot gopherbot added the Proposal label Sep 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.