@@ -6,18 +6,21 @@ module Database.Postgres
66 , ConnectionString ()
77 , mkConnectionString
88 , connect
9+ , disconnect
910 , end
1011 , execute , execute_
1112 , query , query_
1213 , queryValue , queryValue_
1314 , queryOne , queryOne_
1415 , withConnection
16+ , withClient
1517 ) where
1618
1719import Control.Alt
1820import Control.Monad.Eff
1921import Control.Monad.Trans
2022import Data.Either
23+ import Data.Function (Fn2 (), runFn2 )
2124import Data.Array
2225import Data.Foreign
2326import Data.Foreign.Class
@@ -119,6 +122,14 @@ withConnection info p = do
119122 client <- connect info
120123 finally (p client) $ liftEff (end client)
121124
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+
122133liftError :: forall e a . ForeignError -> Aff e a
123134liftError err = throwError $ error (show err)
124135
@@ -146,6 +157,32 @@ foreign import connect' """
146157 }
147158 " " " :: forall eff . String -> Aff (db :: DB | eff ) Client
148159
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+
149186foreign import runQuery_ " " "
150187 function runQuery_(queryStr) {
151188 return function(client) {
@@ -212,3 +249,11 @@ foreign import end """
212249 };
213250 }
214251 " " " :: 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