@@ -263,25 +263,30 @@ export class DatabaseConnection {
263263 * Connect to a PostgreSQL database
264264 */
265265 public async connect ( connectionString ?: string , options : ConnectionOptions = { } ) : Promise < void > {
266- await this . acquireConnectionLease ( ) ;
267- let connectionStateChanged = false ;
266+ // Use environment variable only when no explicit connection string was provided.
267+ const connString = connectionString !== undefined ? connectionString : process . env . POSTGRES_CONNECTION_STRING ;
268+ const effectiveOptions = {
269+ ...getDefaultConnectionOptions ( ) ,
270+ ...options
271+ } ;
272+
273+ if ( connString === undefined || connString . trim ( ) === '' ) {
274+ throw new Error ( 'No non-empty connection string provided and POSTGRES_CONNECTION_STRING environment variable is not set' ) ;
275+ }
268276
269- try {
270- // Use environment variable only when no explicit connection string was provided.
271- const connString = connectionString !== undefined ? connectionString : process . env . POSTGRES_CONNECTION_STRING ;
272- const effectiveOptions = {
273- ...getDefaultConnectionOptions ( ) ,
274- ...options
275- } ;
277+ assertConnectionOptions ( effectiveOptions ) ;
278+ const poolCacheKey = buildPoolCacheKey ( connString , effectiveOptions ) ;
276279
277- if ( connString === undefined || connString . trim ( ) === '' ) {
278- throw new Error ( 'No non-empty connection string provided and POSTGRES_CONNECTION_STRING environment variable is not set' ) ;
279- }
280+ // If already connected to this database, reuse the connection without waiting on our own active lease.
281+ if ( this . pool && this . poolCacheKey === poolCacheKey ) {
282+ return ;
283+ }
280284
281- assertConnectionOptions ( effectiveOptions ) ;
282- const poolCacheKey = buildPoolCacheKey ( connString , effectiveOptions ) ;
285+ await this . acquireConnectionLease ( ) ;
286+ let connectionStateChanged = false ;
283287
284- // If already connected to this database, reuse the connection
288+ try {
289+ // Another queued connect may have established the requested pool while we waited.
285290 if ( this . pool && this . poolCacheKey === poolCacheKey ) {
286291 return ;
287292 }
0 commit comments