@@ -241,19 +241,35 @@ protected Connection newConnection() throws RaiseException, SQLException {
241241 }
242242 throw ex ;
243243 }
244- final PGConnection pgConnection ;
245- if ( connection instanceof PGConnection ) {
246- pgConnection = (PGConnection ) connection ;
244+ // The physical connection is open now; if any of the post-connect
245+ // setup below fails we must close it, otherwise the server-side backend
246+ // leaks (the caller only sees the exception and never gets a handle to
247+ // close). This mirrors the native adapter discarding a connection that
248+ // could not be fully established.
249+ try {
250+ final PGConnection pgConnection ;
251+ if ( connection instanceof PGConnection ) {
252+ pgConnection = (PGConnection ) connection ;
253+ }
254+ else {
255+ pgConnection = connection .unwrap (PGConnection .class );
256+ }
257+ pgConnection .addDataType ("daterange" , DateRangeType .class );
258+ pgConnection .addDataType ("tsrange" , TsRangeType .class );
259+ pgConnection .addDataType ("tstzrange" , TstzRangeType .class );
260+ pgConnection .addDataType ("int4range" , Int4RangeType .class );
261+ pgConnection .addDataType ("int8range" , Int8RangeType .class );
262+ pgConnection .addDataType ("numrange" , NumRangeType .class );
247263 }
248- else {
249- pgConnection = connection .unwrap (PGConnection .class );
264+ catch (SQLException |RuntimeException ex ) {
265+ try {
266+ connection .close ();
267+ }
268+ catch (SQLException closeError ) {
269+ ex .addSuppressed (closeError );
270+ }
271+ throw ex ;
250272 }
251- pgConnection .addDataType ("daterange" , DateRangeType .class );
252- pgConnection .addDataType ("tsrange" , TsRangeType .class );
253- pgConnection .addDataType ("tstzrange" , TstzRangeType .class );
254- pgConnection .addDataType ("int4range" , Int4RangeType .class );
255- pgConnection .addDataType ("int8range" , Int8RangeType .class );
256- pgConnection .addDataType ("numrange" , NumRangeType .class );
257273 return connection ;
258274 }
259275
0 commit comments