Permalink
Browse files

Issue 100: Added context manager support (__enter__ and __exit__).

  • Loading branch information...
1 parent d89d7e9 commit e3a0b3539a62da1362eb90ef1259c7aaec35d838 Michael Kleehammer committed with Aug 30, 2010
Showing with 35 additions and 8 deletions.
  1. +26 −8 src/connection.cpp
  2. +9 −0 tests/sqlservertests.py
View
@@ -858,16 +858,34 @@ Connection_conv_add(Connection* cnxn, PyObject* args)
Py_RETURN_NONE;
}
+static char enter_doc[] = "__enter__() -> self.";
+static PyObject* Connection_enter(PyObject* self)
+{
+ Py_INCREF(self);
+ return self;
+}
+
+static char exit_doc[] = "__exit__(*excinfo) -> None. Closes the connection.";
+static PyObject* Connection_exit(Connection* cnxn, PyObject* args)
+{
+ Connection_clear(cnxn);
+ Py_RETURN_NONE;
+}
+
+
static struct PyMethodDef Connection_methods[] =
{
- { "cursor", (PyCFunction)Connection_cursor, METH_NOARGS, cursor_doc },
- { "close", (PyCFunction)Connection_close, METH_NOARGS, close_doc },
- { "execute", (PyCFunction)Connection_execute, METH_VARARGS, execute_doc },
- { "commit", (PyCFunction)Connection_commit, METH_NOARGS, commit_doc },
- { "rollback", (PyCFunction)Connection_rollback, METH_NOARGS, rollback_doc },
- { "getinfo", (PyCFunction)Connection_getinfo, METH_VARARGS, getinfo_doc },
- { "add_output_converter", (PyCFunction)Connection_conv_add, METH_VARARGS, conv_add_doc },
- { "clear_output_converters", (PyCFunction)Connection_conv_clear, METH_NOARGS, conv_clear_doc },
+ { "cursor", (PyCFunction)Connection_cursor, METH_NOARGS, cursor_doc },
+ { "close", (PyCFunction)Connection_close, METH_NOARGS, close_doc },
+ { "execute", (PyCFunction)Connection_execute, METH_VARARGS, execute_doc },
+ { "commit", (PyCFunction)Connection_commit, METH_NOARGS, commit_doc },
+ { "rollback", (PyCFunction)Connection_rollback, METH_NOARGS, rollback_doc },
+ { "getinfo", (PyCFunction)Connection_getinfo, METH_VARARGS, getinfo_doc },
+ { "add_output_converter", (PyCFunction)Connection_conv_add, METH_VARARGS, conv_add_doc },
+ { "clear_output_converters", (PyCFunction)Connection_conv_clear, METH_NOARGS, conv_clear_doc },
+ { "__enter__", (PyCFunction)Connection_enter, METH_NOARGS, enter_doc },
+ { "__exit__", (PyCFunction)Connection_exit, METH_VARARGS, exit_doc },
+
{ 0, 0, 0, 0 }
};
View
@@ -1160,6 +1160,15 @@ 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)
+
+ # The connection should be closed now.
+ def test():
+ cnxn.getinfo(pyodbc.SQL_DEFAULT_TXN_ISOLATION)
+ self.assertRaises(pyodbc.ProgrammingError, test)
+
def main():
from optparse import OptionParser

0 comments on commit e3a0b35

Please sign in to comment.