@@ -74,6 +74,7 @@ function Postgres(a, b) {
74
74
END : CLOSE ,
75
75
PostgresError,
76
76
options,
77
+ reserve,
77
78
listen,
78
79
begin,
79
80
close,
@@ -199,6 +200,36 @@ function Postgres(a, b) {
199
200
return await sql `select pg_notify(${ channel } , ${ '' + payload } )`
200
201
}
201
202
203
+ async function reserve ( ) {
204
+ const q = Queue ( )
205
+ const c = open . length
206
+ ? open . shift ( )
207
+ : await new Promise ( r => {
208
+ queries . push ( { reserve : r } )
209
+ closed . length && connect ( closed . shift ( ) )
210
+ } )
211
+
212
+ move ( c , reserved )
213
+ c . reserved = ( ) => q . length
214
+ ? c . execute ( q . shift ( ) )
215
+ : move ( c , reserved )
216
+ c . reserved . release = true
217
+
218
+ const sql = Sql ( handler )
219
+ sql . release = ( ) => {
220
+ c . reserved = null
221
+ onopen ( c )
222
+ }
223
+
224
+ return sql
225
+
226
+ function handler ( q ) {
227
+ c . queue === full
228
+ ? q . push ( q )
229
+ : c . execute ( q ) || move ( c , full )
230
+ }
231
+ }
232
+
202
233
async function begin ( options , fn ) {
203
234
! fn && ( fn = options , options = '' )
204
235
const queries = Queue ( )
@@ -270,6 +301,7 @@ function Postgres(a, b) {
270
301
queue === open
271
302
? c . idleTimer . start ( )
272
303
: c . idleTimer . cancel ( )
304
+ return c
273
305
}
274
306
275
307
function json ( x ) {
@@ -348,6 +380,7 @@ function Postgres(a, b) {
348
380
function connect ( c , query ) {
349
381
move ( c , connecting )
350
382
c . connect ( query )
383
+ return c
351
384
}
352
385
353
386
function onend ( c ) {
@@ -361,8 +394,13 @@ function Postgres(a, b) {
361
394
let max = Math . ceil ( queries . length / ( connecting . length + 1 ) )
362
395
, ready = true
363
396
364
- while ( ready && queries . length && max -- > 0 )
365
- ready = c . execute ( queries . shift ( ) )
397
+ while ( ready && queries . length && max -- > 0 ) {
398
+ const query = queries . shift ( )
399
+ if ( query . reserve )
400
+ return query . reserve ( c )
401
+
402
+ ready = c . execute ( query )
403
+ }
366
404
367
405
ready
368
406
? move ( c , busy )
0 commit comments