Skip to content

Commit afff314

Browse files
Vats3dsVats-shivam
andauthored
Provide a context manager for connections (#184) (#187)
Support context managers for pynuodb connections to the database. Note: the exit of the connection will not commit: if there is an open connection on exit it will be rolled back / aborted. Co-authored-by: Vats Shivam <[email protected]>
1 parent b9872c5 commit afff314

File tree

3 files changed

+29
-11
lines changed

3 files changed

+29
-11
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,5 @@ results/
4848
.pydevproject
4949
.settings
5050
.idea
51+
venv
52+

pynuodb/connection.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,3 +350,20 @@ def cursor(self, prepared_statement_cache_size=50):
350350
"""
351351
self._check_closed()
352352
return cursor.Cursor(self.__session, prepared_statement_cache_size)
353+
354+
def __enter__(self):
355+
# type: () -> Connection
356+
"""Returns the NuoDB SQL Connection object itself to be used within the context block."""
357+
return self
358+
359+
def __exit__(self, exc_type, # type: Optional[Type[BaseException]]
360+
exc_val, # type: Optional[BaseException]
361+
exc_tb, # type: Optional[Any]
362+
):
363+
# type: (...) -> None
364+
"""Exits the runtime context, closing the connection.
365+
366+
This immediately closes the connection, which destroys all cursors
367+
created by it and rolls back any uncommitted transactions.
368+
"""
369+
self.close()

tests/nuodb_date_time_test.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
"""
88

99
import datetime
10-
from contextlib import closing
1110
import pytest
1211
from pynuodb.exception import ProgrammingError
1312
from .mock_tzs import localize, UTC, TimeZoneInfo
@@ -42,7 +41,7 @@ def test_nonnaive_timestamps(self):
4241
local_dt = localize(dt, TimeZoneInfo('America/New_York'))
4342
pst_dt = localize(dt, TimeZoneInfo('America/Los_Angeles'))
4443

45-
with closing(self._connect(options={'TimeZone': 'America/Chicago'})) as con:
44+
with self._connect(options={'TimeZone': 'America/Chicago'}) as con:
4645
cursor = con.cursor()
4746
cursor.execute("drop table if exists NONNAIVE")
4847
cursor.execute("create table NONNAIVE(tstamp datetime, dtstr string)")
@@ -77,7 +76,7 @@ def test_pre_1900_date(self):
7776
# type: () -> None
7877
"""Test insert and query of dates before 1900"""
7978

80-
with closing(self._connect(options={'TimeZone': 'EST5EDT'})) as con:
79+
with self._connect(options={'TimeZone': 'EST5EDT'}) as con:
8180
cursor = con.cursor()
8281
cursor.execute("create temporary table HISTORY(day date)")
8382
cursor.execute("insert into HISTORY VALUES ('November 19, 1863')")
@@ -102,7 +101,7 @@ def test_daylight_savings_time(self):
102101
# type: () -> None
103102
"""Test read dates either in daylight saving time or not"""
104103

105-
with closing(self._connect(options={'TimeZone': 'America/New_York'})) as con:
104+
with self._connect(options={'TimeZone': 'America/New_York'}) as con:
106105
cursor = con.cursor()
107106

108107
tz = TimeZoneInfo('America/New_York')
@@ -118,7 +117,7 @@ def test_daylight_savings_time(self):
118117
nytime = row[0].astimezone(tz)
119118
assert nytime.hour == 20
120119

121-
with closing(self._connect(options={'TimeZone': 'Pacific/Auckland'})) as con:
120+
with self._connect(options={'TimeZone': 'Pacific/Auckland'}) as con:
122121
tz = TimeZoneInfo('Pacific/Auckland')
123122
cursor = con.cursor()
124123
cursor.execute("select TIMESTAMP'2010-01-01 20:01:21' from DUAL")
@@ -143,7 +142,7 @@ def test_gregorian_date(self):
143142
valid dates per the switch over.
144143
"""
145144

146-
with closing(self._connect(options={'TimeZone': 'EST5EDT'})) as con:
145+
with self._connect(options={'TimeZone': 'EST5EDT'}) as con:
147146
cursor = con.cursor()
148147
ddl = (
149148
"create temporary table HISTORY(day string, "
@@ -173,7 +172,7 @@ def test_microseconds(self):
173172
# type: () -> None
174173
"""Test timestamps with microseconds set before or after epoch"""
175174

176-
with closing(self._connect(options={'TimeZone': 'EST5EDT'})) as con:
175+
with self._connect(options={'TimeZone': 'EST5EDT'}) as con:
177176
cursor = con.cursor()
178177

179178
dt = datetime.datetime(year=1990, month=1, day=1, hour=1,
@@ -211,7 +210,7 @@ def test_microseconds(self):
211210

212211
def test_time_wraps_read(self):
213212

214-
with closing(self._connect(options={'TimeZone': 'Pacific/Auckland'})) as con:
213+
with self._connect(options={'TimeZone': 'Pacific/Auckland'}) as con:
215214
cursor = con.cursor()
216215
# GMT is 1990-05-31 21:00:01.2
217216
cursor.execute("select CAST(TIMESTAMP'1990-06-01 9:00:01.2' AS TIME) from dual")
@@ -221,7 +220,7 @@ def test_time_wraps_read(self):
221220
assert row[0].second == 1
222221
assert row[0].microsecond == 200000
223222

224-
with closing(self._connect(options={'TimeZone': 'Pacific/Honolulu'})) as con:
223+
with self._connect(options={'TimeZone': 'Pacific/Honolulu'}) as con:
225224
cursor = con.cursor()
226225
# GMT is 1990-06-02 05:00:01.2
227226
cursor.execute("select CAST(TIMESTAMP'1990-06-01 19:00:01.2' AS TIME) from dual")
@@ -269,7 +268,7 @@ def test_time_wraps_west_write(self):
269268
CONNTZ = "America/Chicago"
270269
GMT = "GMT"
271270

272-
with closing(self._connect(options={'TimeZone': CONNTZ})) as con:
271+
with self._connect(options={'TimeZone': CONNTZ}) as con:
273272
cursor = con.cursor()
274273
cursor.execute('drop table WESTTZ if exists')
275274
cursor.execute("create table WESTTZ ( t TIME, t_as_string TIME, dt TIME)")
@@ -346,7 +345,7 @@ def test_time_wraps_east_write(self):
346345
EASTTZ = "America/Chicago"
347346
GMT = "GMT"
348347

349-
with closing(self._connect(options={'TimeZone': CONNTZ})) as con:
348+
with self._connect(options={'TimeZone': CONNTZ}) as con:
350349
cursor = con.cursor()
351350
cursor.execute('drop table EASTTZ if exists')
352351
cursor.execute("create table EASTTZ ( t TIME, t_as_string TIME, dt TIME)")

0 commit comments

Comments
 (0)