@@ -6,6 +6,7 @@ module Database.Postgres
66 , ConnectionString ()
77 , mkConnectionString
88 , connect
9+ , disconnect
910 , end
1011 , execute , execute_
1112 , query , query_
@@ -18,6 +19,7 @@ import Control.Alt
1819import Control.Monad.Eff
1920import Control.Monad.Trans
2021import Data.Either
22+ import Data.Function (Fn2 (), runFn2 )
2123import Data.Array
2224import Data.Foreign
2325import Data.Foreign.Class
@@ -115,20 +117,11 @@ withConnection :: forall eff a
115117 . ConnectionInfo
116118 -> (Client -> Aff (db :: DB | eff ) a )
117119 -> Aff (db :: DB | eff ) a
118- withConnection info p = do
119- client <- connect info
120- finally (p client) $ liftEff (end client)
120+ withConnection info p = runFn2 _withConnection (mkConnectionString info) p
121121
122122liftError :: forall e a . ForeignError -> Aff e a
123123liftError err = throwError $ error (show err)
124124
125- finally :: forall eff a . Aff eff a -> Aff eff Unit -> Aff eff a
126- finally a sequel = do
127- res <- attempt a
128- sequel
129- either throwError pure res
130-
131-
132125foreign import connect' " " "
133126 function connect$prime(conString) {
134127 return function(success, error) {
@@ -146,6 +139,32 @@ foreign import connect' """
146139 }
147140 " " " :: forall eff . String -> Aff (db :: DB | eff ) Client
148141
142+ foreign import _withConnection
143+ " " "
144+ function _withConnection(conString, cb) {
145+ return function(success, error) {
146+ var pg = require('pg');
147+ pg.connect(conString, function(err, client, done) {
148+ if (err) {
149+ done(true);
150+ return error(err);
151+ }
152+ cb(client)(function(v) {
153+ done();
154+ success(v);
155+ }, function(err) {
156+ done();
157+ error(err);
158+ })
159+ });
160+ };
161+ }
162+ " " " :: forall eff a .
163+ Fn2
164+ ConnectionString
165+ (Client -> Aff (db :: DB | eff ) a )
166+ (Aff (db :: DB | eff ) a )
167+
149168foreign import runQuery_ " " "
150169 function runQuery_(queryStr) {
151170 return function(client) {
@@ -212,3 +231,11 @@ foreign import end """
212231 };
213232 }
214233 " " " :: forall eff . Client -> Eff (db :: DB | eff ) Unit
234+
235+ foreign import disconnect
236+ " " "
237+ function disconnect() {
238+ var pg = require('pg');
239+ pg.end();
240+ }
241+ " " " :: forall eff . Eff (db :: DB | eff ) Unit
0 commit comments