Skip to content

Commit d90f60e

Browse files
authored
Merge pull request #1219 from skunkworker/pr/pg-connection-leak-fix
Draft: Fix PostgreSQL server-side connection leak on failed establishment (too many clients)
2 parents 4c2d48e + 9c29290 commit d90f60e

1 file changed

Lines changed: 27 additions & 11 deletions

File tree

src/java/arjdbc/postgresql/PostgreSQLRubyJdbcConnection.java

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)