Given that db
is of type *sql.DB
(uging lib/pq
driver), the following code causes connection leak:
rows, err := db.Query(
"select 1 from things where id = $1",
thing,
)
if err != nil {
return nil, fmt.Errorf("can't select thing (%d): %w", thing, err)
}
found := false
for rows.Next() {
found = true
break
}
Calling this code repeatedly increases the number of open connections, until exhausted:
select sum(numbackends) from pg_stat_database;
// 5
// 6
// 7
// ...
// 80
How do I fix it?