@@ -74,6 +74,7 @@ function Postgres(a, b) {
7474 END : CLOSE ,
7575 PostgresError,
7676 options,
77+ reserve,
7778 listen,
7879 begin,
7980 close,
@@ -199,6 +200,36 @@ function Postgres(a, b) {
199200 return await sql `select pg_notify(${ channel } , ${ '' + payload } )`
200201 }
201202
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+
202233 async function begin ( options , fn ) {
203234 ! fn && ( fn = options , options = '' )
204235 const queries = Queue ( )
@@ -270,6 +301,7 @@ function Postgres(a, b) {
270301 queue === open
271302 ? c . idleTimer . start ( )
272303 : c . idleTimer . cancel ( )
304+ return c
273305 }
274306
275307 function json ( x ) {
@@ -348,6 +380,7 @@ function Postgres(a, b) {
348380 function connect ( c , query ) {
349381 move ( c , connecting )
350382 c . connect ( query )
383+ return c
351384 }
352385
353386 function onend ( c ) {
@@ -361,8 +394,13 @@ function Postgres(a, b) {
361394 let max = Math . ceil ( queries . length / ( connecting . length + 1 ) )
362395 , ready = true
363396
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+ }
366404
367405 ready
368406 ? move ( c , busy )
0 commit comments