Commits

Mikhail Denisenko  committed 2df06f5

wrapping of django IntegrityError and DatabaseException

  • Participants
  • Parent commits e2acb97

Comments (0)

Files changed (1)

File django_pytds/base.py

 """Microsoft SQL Server database backend for Django."""
+import sys
+
+from django.db import utils
 from django.db.backends import BaseDatabaseWrapper, BaseDatabaseFeatures, BaseDatabaseValidation, BaseDatabaseClient
 from django.db.backends.signals import connection_created
 
     def _cursor(self):
         if self.connection is None:
             self.__connect()
-        return self.connection.cursor()
+        return CursorWrapper(self.connection.cursor())
 
     def disable_constraint_checking(self):
         """
                 cursor.execute('DBCC CHECKCONSTRAINTS({0})'.format(
                     qn(name)
                 ))
+
+
+class CursorWrapper(object):
+    def __init__(self, cursor):
+        self.cursor = cursor
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, type, value, traceback):
+        self.cursor.close()
+
+    def execute(self, sql, params = ()):
+        try:
+            return self.cursor.execute(sql, params)
+        except Database.IntegrityError, e:
+            raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
+        except Database.DatabaseError, e:
+            raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
+
+    def executemany(self, sql, params):
+        try:
+            return self.cursor.executemany(sql, params)
+        except Database.IntegrityError, e:
+            raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
+        except Database.DatabaseError, e:
+            raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
+
+    def __getattr__(self, attr):
+        if attr in self.__dict__:
+            return self.__dict__[attr]
+        else:
+            return getattr(self.cursor, attr)
+
+    def __iter__(self):
+        return iter(self.cursor)