The following code is extracted from asyncpg.
template withConnection*(pool: apgPool, conn, body: untyped) =
## Retrieves first available connection from pool, assign it
## to variable with name `conn`. You can use this connection
## inside withConnection code block.
mixin getFreeConnection
var connFuture = getFreeConnection(pool)
yield connFuture
var index = connFuture.read
block:
var conn = pool.connections[index]
body
pool.futures[index].complete()
When code in 'body' raise a exception, the last line
"pool.future[index].complete()" will not be executed and the connection in the
pool will be leaked. Wrapper the body in a proc is not possible when body
contains async call itself. I have no idea how to make the above code works
right.