pgtoolkit/pgmanager.py
changeset 46 037410ef2b6b
parent 45 6d8e4ee4bdd2
child 48 b82c7c2fb5af
--- a/pgtoolkit/pgmanager.py	Wed Sep 26 16:43:53 2012 +0200
+++ b/pgtoolkit/pgmanager.py	Wed Sep 26 23:29:54 2012 +0200
@@ -143,18 +143,28 @@
 class Cursor(psycopg2.extensions.cursor):
 
     def execute(self, query, args=None):
-        self._log_query(query, args)
         try:
             return super(Cursor, self).execute(query, args)
         except DatabaseError:
+            # log query and exception
+            self._log_query(query, args)
             self._log_exception()
+            raise
+        else:
+            # log query from self.query
+            self._log_query()
 
     def callproc(self, procname, args=None):
-        self._log_query('CALL %s(%s)' % (procname, ','.join(args)))
         try:
             return super(Cursor, self).callproc(procname, args)
         except DatabaseError:
+            # log query and exception
+            self._log_query(self._build_callproc_query(procname, len(args)), args)
             self._log_exception()
+            raise
+        else:
+            # log query from self.query
+            self._log_query()
 
     def row_dict(self, row, lstrip=None):
         adjustname = lambda a: a
@@ -202,14 +212,19 @@
         rows = super(Cursor, self).fetchall()
         return [self.row_dict([self.mogrify('%s', [x]).decode('utf8') for x in row], lstrip) for row in rows]
 
-    def _log_query(self, query, args=None):
+    def _log_query(self, query='?', args=None):
         name = self.connection.name if hasattr(self.connection, 'name') else '-'
-        log_sql.info('[%s] %s' % (name, self.mogrify(query, args).decode('utf8')))
+        query = self.query or self.mogrify(query, args)
+        log_sql.info('[%s] %s' % (name, query.decode('utf8')))
 
     def _log_exception(self):
         name = self.connection.name if hasattr(self.connection, 'name') else '-'
         log_sql.exception('[%s] exception:' % (name,))
 
+    def _build_callproc_query(self, procname, num_args):
+        return 'SELECT * FROM %s(%s)' %(procname, ', '.join('%s'))
+
+
 class Connection(psycopg2.extensions.connection):
 
     def cursor(self, name=None):