Skip to content

Commit 1e7b755

Browse files
author
James William Pye
committed
Ensure that the socket is closed on connection close. (3.2 ResourceWarning fixes)
1 parent 655fc89 commit 1e7b755

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

postgresql/driver/pq3.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2293,26 +2293,27 @@ def cursor_from_id(self, cursor_id : str) -> Cursor:
22932293

22942294
@property
22952295
def closed(self) -> bool:
2296-
if not hasattr(self, 'pq'):
2296+
if getattr(self, 'pq', None) is None:
22972297
return True
22982298
if hasattr(self.pq, 'socket') and self.pq.xact is not None:
22992299
return self.pq.xact.fatal is True
23002300
return False
23012301

2302-
def close(self):
2302+
def close(self, getattr = getattr):
23032303
if self.closed:
23042304
return
23052305
# Write out the disconnect message if the socket is around.
23062306
# If the connection is known to be lost, don't bother. It will
23072307
# generate an extra exception.
2308-
x = self.pq.xact
2308+
x = getattr(self.pq, 'xact', None)
23092309
if x:
23102310
# don't raise?
23112311
self.pq.complete()
23122312
if self.closed:
23132313
return
23142314
self.pq.push(xact.Closing())
23152315
self.pq.complete()
2316+
self.pq.socket.close()
23162317

23172318
@property
23182319
def state(self) -> str:
@@ -2347,13 +2348,22 @@ def connect(self):
23472348
if self.closed is False:
23482349
# already connected? just return.
23492350
return
2350-
# It's closed.
23512351

23522352
if hasattr(self, 'pq'):
23532353
# It's closed, *but* there's a PQ connection..
23542354
x = self.pq.xact
23552355
self.typio.raise_error(x.error_message, cause = getattr(x, 'exception', None), creator = self)
23562356

2357+
# It's closed.
2358+
try:
2359+
self._establish()
2360+
except Exception:
2361+
# Close it up on failure.
2362+
self.close()
2363+
raise
2364+
2365+
def _establish(self):
2366+
# guts of connect()
23572367
self.pq = None
23582368
# if any exception occurs past this point, the connection
23592369
# will not be usable.

0 commit comments

Comments
 (0)