@@ -6,6 +6,7 @@ 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_
@@ -18,6 +19,7 @@ import Control.Alt
18
19
import Control.Monad.Eff
19
20
import Control.Monad.Trans
20
21
import Data.Either
22
+ import Data.Function (Fn2 (), runFn2 )
21
23
import Data.Array
22
24
import Data.Foreign
23
25
import Data.Foreign.Class
@@ -115,20 +117,11 @@ withConnection :: forall eff a
115
117
. ConnectionInfo
116
118
-> (Client -> Aff (db :: DB | eff ) a )
117
119
-> 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
121
121
122
122
liftError :: forall e a . ForeignError -> Aff e a
123
123
liftError err = throwError $ error (show err)
124
124
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
-
132
125
foreign import connect' " " "
133
126
function connect$prime(conString) {
134
127
return function(success, error) {
@@ -146,6 +139,32 @@ foreign import connect' """
146
139
}
147
140
" " " :: forall eff . String -> Aff (db :: DB | eff ) Client
148
141
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
+
149
168
foreign import runQuery_ " " "
150
169
function runQuery_(queryStr) {
151
170
return function(client) {
@@ -212,3 +231,11 @@ foreign import end """
212
231
};
213
232
}
214
233
" " " :: 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