<p>I recently encountered a PostgreSQL connection leak due to my forgetting to close a <em>database/sql</em> 'rows' object. I only discovered this after adding enough unit tests to max out my Postgres connection limit. Is there a clean way to reliably detect this mistake in test that doesn't rely on such a coincidence?</p>
<hr/>**评论:**<br/><br/>cs-guy: <pre><p>Try this: At the beginning of your test call <code>db.MaxIdleConns(0)</code>. Before your test exits verify that <code>db.Stats().OpenConnections == 0</code>.</p></pre>UniverseCity: <pre><p>Exits*</p></pre>kardianos: <pre><p>This is kinda an aside:
I'm working on a v2 of my rdb (relational db interface) package. This release will include support for context. Every query will have a context associated with it. Once that context is done (which should be when the request is done) that query/db conn will be finished and returned to the pool. Thus so long as your request have a context with a deadline associated with it that get's canceled when the request is done, database connections won't leak.</p>
<p>I know that doesn't help you now... but...</p></pre>watr: <pre><p>What's your lib's name?</p></pre>tusharsingh: <pre><p>Wrap your DB connection with a struct that implements query, exec, etc. the common calls that you use. Use this struct for your DB connection with an embedded sql.DB.</p>
<p>You can then include counter code or locks to see if you're leaving anything behind.</p>
<p>The way I've used it in dev/testing is to only allow one query at a time to prevent overlapping requests that haven't been closed. The program panics if you open a new query while still using an existing conn.</p></pre>bloodqc: <pre><p>Maybe with <a href="https://golang.org/pkg/database/sql/#DBStats" rel="nofollow">DBStats</a>. There's <code>OpenConnections</code> but I don't know if connections are kept open for better performance.</p></pre>warmans: <pre><p>I think they're easy to spot if you have telemetry data graphed out e.g. with Prometheus. Even just logging go routines would show leaks clearly on a graph since I think an open db cursor creates a gorourine. Another package like pprof would give you more info to actually fix the issue.
A test would be better but having the graphs is a good catchall for this kind of thing.</p></pre>
![](https://static.golangjob.cn/static/img/banner.png)