Skip to content

Commit

Permalink
Issue 199: with cxn: doesn't commit on success
Browse files Browse the repository at this point in the history
  • Loading branch information
mkleehammer committed Aug 21, 2011
1 parent 0d47ebe commit a6b400f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
7 changes: 6 additions & 1 deletion src/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -883,7 +883,12 @@ static PyObject* Connection_enter(PyObject* self)
static char exit_doc[] = "__exit__(*excinfo) -> None. Closes the connection.";
static PyObject* Connection_exit(Connection* cnxn, PyObject* args)
{
Connection_clear(cnxn);
// If an error has occurred, `args` will be a tuple of 3 values. Otherwise it will be a tuple of 3 `None`s.
I(PyTuple_Check(args));

if (cnxn->nAutoCommit == SQL_AUTOCOMMIT_OFF && PyTuple_GetItem(args, 0) == Py_None)
SQLEndTran(SQL_HANDLE_DBC, cnxn->hdbc, SQL_COMMIT);

Py_RETURN_NONE;
}

Expand Down
25 changes: 18 additions & 7 deletions tests/sqlservertests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1232,14 +1232,25 @@ def test_row_gtlt(self):
rows = list(rows)
rows.sort() # uses <

def test_context_manager(self):
with pyodbc.connect(self.connection_string) as cnxn:
cnxn.getinfo(pyodbc.SQL_DEFAULT_TXN_ISOLATION)
def test_context_manager_success(self):

self.cursor.execute("create table t1(n int)")
self.cnxn.commit()

try:
with pyodbc.connect(self.connection_string) as cnxn:
cursor = cnxn.cursor()
cursor.execute("insert into t1 values (1)")
except Exception:
pass

cnxn = None
cursor = None

rows = self.cursor.execute("select n from t1").fetchall()
self.assertEquals(len(rows), 1)
self.assertEquals(rows[0][0], 1)

# The connection should be closed now.
def test():
cnxn.getinfo(pyodbc.SQL_DEFAULT_TXN_ISOLATION)
self.assertRaises(pyodbc.ProgrammingError, test)

def test_untyped_none(self):
# From issue 129
Expand Down

0 comments on commit a6b400f

Please sign in to comment.