1
1
var EventEmitter = require ( 'events' ) . EventEmitter ;
2
+ var sys = require ( 'sys' ) ;
2
3
var Client = require ( __dirname + '/client' ) ;
3
4
var defaults = require ( __dirname + '/defaults' ) ;
4
5
var genericPool = require ( 'generic-pool' ) ;
@@ -7,7 +8,8 @@ var genericPool = require('generic-pool');
7
8
var pools = { } ;
8
9
9
10
//returns connect function using supplied client constructor
10
- var makeConnectFunction = function ( ClientConstructor ) {
11
+ var makeConnectFunction = function ( pg ) {
12
+ var ClientConstructor = pg . Client ;
11
13
return function ( config , callback ) {
12
14
var c = config ;
13
15
var cb = callback ;
@@ -31,6 +33,13 @@ var makeConnectFunction = function(ClientConstructor) {
31
33
} ;
32
34
var connectSuccess = function ( ) {
33
35
client . removeListener ( 'error' , connectError ) ;
36
+
37
+ //handle connected client background errors by emitting event
38
+ //via the pg object and then removing errored client from the pool
39
+ client . on ( 'error' , function ( e ) {
40
+ pg . emit ( 'error' , e , client ) ;
41
+ pool . destroy ( client ) ;
42
+ } ) ;
34
43
callback ( null , client ) ;
35
44
} ;
36
45
client . once ( 'connect' , connectSuccess ) ;
@@ -58,25 +67,25 @@ var end = function() {
58
67
} )
59
68
} ;
60
69
61
- module . exports = {
62
- Client : Client ,
63
- Connection : require ( __dirname + '/connection' ) ,
64
- connect : makeConnectFunction ( Client ) ,
65
- end : end ,
66
- defaults : defaults
67
- }
70
+ var PG = function ( clientConstructor ) {
71
+ EventEmitter . call ( this ) ;
72
+ this . Client = clientConstructor ;
73
+ this . Connection = require ( __dirname + '/connection' ) ;
74
+ this . connect = makeConnectFunction ( this ) ;
75
+ this . end = end ;
76
+ this . defaults = defaults ;
77
+ } ;
78
+
79
+ sys . inherits ( PG , EventEmitter ) ;
80
+
81
+ module . exports = new PG ( Client ) ;
68
82
69
83
var nativeExport = null ;
70
84
//lazy require native module...the c++ may not have been compiled
71
85
module . exports . __defineGetter__ ( "native" , function ( ) {
72
86
if ( nativeExport === null ) {
73
87
var NativeClient = require ( __dirname + '/native' ) ;
74
- nativeExport = {
75
- Client : NativeClient ,
76
- connect : makeConnectFunction ( NativeClient ) ,
77
- end : end ,
78
- defaults : defaults
79
- }
88
+ nativeExport = new PG ( NativeClient ) ;
80
89
}
81
90
return nativeExport ;
82
91
} )
0 commit comments