@@ -6,18 +6,21 @@ module Database.Postgres
6
6
, ConnectionString ()
7
7
, mkConnectionString
8
8
, connect
9
+ , disconnect
9
10
, end
10
11
, execute , execute_
11
12
, query , query_
12
13
, queryValue , queryValue_
13
14
, queryOne , queryOne_
14
15
, withConnection
16
+ , withClient
15
17
) where
16
18
17
19
import Control.Alt
18
20
import Control.Monad.Eff
19
21
import Control.Monad.Trans
20
22
import Data.Either
23
+ import Data.Function (Fn2 (), runFn2 )
21
24
import Data.Array
22
25
import Data.Foreign
23
26
import Data.Foreign.Class
@@ -119,6 +122,14 @@ withConnection info p = do
119
122
client <- connect info
120
123
finally (p client) $ liftEff (end client)
121
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
132
+
122
133
liftError :: forall e a . ForeignError -> Aff e a
123
134
liftError err = throwError $ error (show err)
124
135
@@ -146,6 +157,32 @@ foreign import connect' """
146
157
}
147
158
" " " :: forall eff . String -> Aff (db :: DB | eff ) Client
148
159
160
+ foreign import _withClient
161
+ " " "
162
+ function _withClient(conString, cb) {
163
+ return function(success, error) {
164
+ var pg = require('pg');
165
+ pg.connect(conString, function(err, client, done) {
166
+ if (err) {
167
+ done(true);
168
+ return error(err);
169
+ }
170
+ cb(client)(function(v) {
171
+ done();
172
+ success(v);
173
+ }, function(err) {
174
+ done();
175
+ error(err);
176
+ })
177
+ });
178
+ };
179
+ }
180
+ " " " :: forall eff a .
181
+ Fn2
182
+ ConnectionString
183
+ (Client -> Aff (db :: DB | eff ) a )
184
+ (Aff (db :: DB | eff ) a )
185
+
149
186
foreign import runQuery_ " " "
150
187
function runQuery_(queryStr) {
151
188
return function(client) {
@@ -212,3 +249,11 @@ foreign import end """
212
249
};
213
250
}
214
251
" " " :: forall eff . Client -> Eff (db :: DB | eff ) Unit
252
+
253
+ foreign import disconnect
254
+ " " "
255
+ function disconnect() {
256
+ var pg = require('pg');
257
+ pg.end();
258
+ }
259
+ " " " :: forall eff . Eff (db :: DB | eff ) Unit
0 commit comments