@@ -13,6 +13,7 @@ module Database.Postgres
1313 , queryValue , queryValue_
1414 , queryOne , queryOne_
1515 , withConnection
16+ , withClient
1617 ) where
1718
1819import Control.Alt
@@ -117,11 +118,28 @@ withConnection :: forall eff a
117118 . ConnectionInfo
118119 -> (Client -> Aff (db :: DB | eff ) a )
119120 -> Aff (db :: DB | eff ) a
120- withConnection info p = runFn2 _withConnection (mkConnectionString info) p
121+ withConnection info p = do
122+ client <- connect info
123+ finally (p client) $ liftEff (end client)
124+
125+ -- | Takes a Client from the connection pool, runs the given function with
126+ -- | the client and returns the results.
127+ withClient :: forall eff a
128+ . ConnectionInfo
129+ -> (Client -> Aff (db :: DB | eff ) a )
130+ -> Aff (db :: DB | eff ) a
131+ withClient info p = runFn2 _withClient (mkConnectionString info) p
121132
122133liftError :: forall e a . ForeignError -> Aff e a
123134liftError err = throwError $ error (show err)
124135
136+ finally :: forall eff a . Aff eff a -> Aff eff Unit -> Aff eff a
137+ finally a sequel = do
138+ res <- attempt a
139+ sequel
140+ either throwError pure res
141+
142+
125143foreign import connect' " " "
126144 function connect$prime(conString) {
127145 return function(success, error) {
@@ -139,9 +157,9 @@ foreign import connect' """
139157 }
140158 " " " :: forall eff . String -> Aff (db :: DB | eff ) Client
141159
142- foreign import _withConnection
160+ foreign import _withClient
143161 " " "
144- function _withConnection (conString, cb) {
162+ function _withClient (conString, cb) {
145163 return function(success, error) {
146164 var pg = require('pg');
147165 pg.connect(conString, function(err, client, done) {
0 commit comments