Skip to content

Commit 3e73da6

Browse files
committed
Close cursor during __exit__; #18
1 parent 4913060 commit 3e73da6

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

postgres.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -505,11 +505,13 @@ def __enter__(self):
505505
"""Get a connection from the pool.
506506
"""
507507
self.conn = self.pool.getconn()
508-
return self.conn.cursor(*self.a, **self.kw)
508+
self.cursor = self.conn.cursor(*self.a, **self.kw)
509+
return self.cursor
509510

510511
def __exit__(self, *exc_info):
511512
"""Put our connection back in the pool.
512513
"""
514+
self.cursor.close()
513515
self.pool.putconn(self.conn)
514516

515517

@@ -540,7 +542,8 @@ def __enter__(self):
540542
"""
541543
self.conn = self.pool.getconn()
542544
self.conn.autocommit = False
543-
return self.conn.cursor(*self.a, **self.kw)
545+
self.cursor = self.conn.cursor(*self.a, **self.kw)
546+
return self.cursor
544547

545548
def __exit__(self, *exc_info):
546549
"""Put our connection back in the pool.
@@ -549,6 +552,7 @@ def __exit__(self, *exc_info):
549552
self.conn.commit()
550553
else:
551554
self.conn.rollback()
555+
self.cursor.close()
552556
self.conn.autocommit = True
553557
self.pool.putconn(self.conn)
554558

tests.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from postgres import Postgres, TooFew, TooMany
88
from psycopg2.extras import NamedTupleCursor
9+
from psycopg2 import InterfaceError
910

1011

1112
DATABASE_URL = os.environ['DATABASE_URL']
@@ -233,6 +234,13 @@ def test_we_can_use_cursor_closed(self):
233234
actual = cursor.closed
234235
assert not actual
235236

237+
def test_we_close_the_cursor(self):
238+
with self.db.get_cursor() as cursor:
239+
cursor.execute("SELECT * FROM foo ORDER BY bar")
240+
self.assertRaises( InterfaceError
241+
, cursor.fetchall
242+
)
243+
236244

237245
# db.get_transaction
238246
# ==================
@@ -272,6 +280,13 @@ class Heck(Exception): pass
272280
actual = self.db.all("SELECT * FROM foo ORDER BY bar")
273281
assert actual == [{"bar": "baz"}, {"bar": "buz"}]
274282

283+
def test_we_close_the_cursor(self):
284+
with self.db.get_transaction() as txn:
285+
txn.execute("SELECT * FROM foo ORDER BY bar")
286+
self.assertRaises( InterfaceError
287+
, txn.fetchall
288+
)
289+
275290

276291
# db.get_connection
277292
# =================

0 commit comments

Comments
 (0)