Skip to content

Commit

Permalink
database: Close query rows before returning
Browse files Browse the repository at this point in the history
  • Loading branch information
beautifulentropy committed Sep 12, 2024
1 parent 990ad07 commit 62c3b29
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
8 changes: 8 additions & 0 deletions cmd/contact-auditor/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,14 @@ func (c contactAuditor) run(ctx context.Context, resChan chan *result) error {
resChan <- &result{id, contacts, createdAt}
}
}

err = rows.Err()
if err != nil {
// It's okay to return here, an abnormal termination automatically calls
// rows.Close(): http://go-database-sql.org/errors.html
return fmt.Errorf("querying db: %w", err)
}

// Ensure the query wasn't interrupted before it could complete.
err = rows.Close()
if err != nil {
Expand Down
7 changes: 7 additions & 0 deletions db/multi.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,13 @@ func (mi *MultiInserter) Insert(ctx context.Context, queryer Queryer) ([]int64,
}
}

err = rows.Err()
if err != nil {
// It's okay to return here, an abnormal termination automatically calls
// rows.Close(): http://go-database-sql.org/errors.html
return nil, fmt.Errorf("querying db: %w", err)
}

// Hack: sometimes in unittests we make a mock Queryer that returns a nil
// `*sql.Rows`. A nil `*sql.Rows` is not actually valid— calling `Close()`
// on it will panic— but here we choose to treat it like an empty list,
Expand Down
12 changes: 11 additions & 1 deletion test/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,5 +122,15 @@ func allTableNamesInDB(ctx context.Context, db CleanUpDB) ([]string, error) {
}
ts = append(ts, tableName)
}
return ts, r.Err()
err = r.Err()
if err != nil {
// It's okay to return here, an abnormal termination automatically calls
// rows.Close(): http://go-database-sql.org/errors.html
return nil, err
}
err = r.Close()
if err != nil {
return nil, err
}
return ts, nil
}

0 comments on commit 62c3b29

Please sign in to comment.