@@ -13,6 +13,7 @@ module Database.Postgres
13
13
, queryValue , queryValue_
14
14
, queryOne , queryOne_
15
15
, withConnection
16
+ , withClient
16
17
) where
17
18
18
19
import Control.Alt
@@ -117,11 +118,28 @@ withConnection :: forall eff a
117
118
. ConnectionInfo
118
119
-> (Client -> Aff (db :: DB | eff ) a )
119
120
-> 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
121
132
122
133
liftError :: forall e a . ForeignError -> Aff e a
123
134
liftError err = throwError $ error (show err)
124
135
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
+
125
143
foreign import connect' " " "
126
144
function connect$prime(conString) {
127
145
return function(success, error) {
@@ -139,9 +157,9 @@ foreign import connect' """
139
157
}
140
158
" " " :: forall eff . String -> Aff (db :: DB | eff ) Client
141
159
142
- foreign import _withConnection
160
+ foreign import _withClient
143
161
" " "
144
- function _withConnection (conString, cb) {
162
+ function _withClient (conString, cb) {
145
163
return function(success, error) {
146
164
var pg = require('pg');
147
165
pg.connect(conString, function(err, client, done) {
0 commit comments