[MERGE] addons 16 survey
[odoo/odoo.git] / openerp / sql_db.py
index 931804a..f18414b 100644 (file)
@@ -138,6 +138,16 @@ class Cursor(object):
         sure you use psycopg2 v2.4.2 or newer if you use PostgreSQL 9.1 and
         the performance hit is a concern for you.
 
+        .. attribute:: cache
+
+            Cache dictionary with a "request" (-ish) lifecycle, only lives as
+            long as the cursor itself does and proactively cleared when the
+            cursor is closed.
+
+            This cache should *only* be used to store repeatable reads as it
+            ignores rollbacks and savepoints, it should not be used to store
+            *any* data which may be modified during the life of the cursor.
+
     """
     IN_MAX = 1000 # decent limit on size of IN queries - guideline = Oracle limit
 
@@ -182,6 +192,8 @@ class Cursor(object):
 
         self._default_log_exceptions = True
 
+        self.cache = {}
+
     def __del__(self):
         if not self.__closed and not self._cnx.closed:
             # Oops. 'self' has not been closed explicitly.
@@ -194,15 +206,18 @@ class Cursor(object):
                 msg += "Cursor was created at %s:%s" % self.__caller
             else:
                 msg += "Please enable sql debugging to trace the caller."
-            _logger.warn(msg)
+            _logger.warning(msg)
             self._close(True)
 
     @check
     def execute(self, query, params=None, log_exceptions=None):
         if '%d' in query or '%f' in query:
-            _logger.warn(query)
-            _logger.warn("SQL queries cannot contain %d or %f anymore. "
+            _logger.warning(query)
+            _logger.warning("SQL queries cannot contain %d or %f anymore. "
                          "Use only %s")
+        if params and not isinstance(params, (tuple, list, dict)):
+            _logger.error("SQL query parameters should be a tuple, list or dict; got %r", params)
+            raise ValueError("SQL query parameters should be a tuple, list or dict; got %r" % (params,))
 
         if self.sql_log:
             now = mdt.now()
@@ -223,7 +238,7 @@ class Cursor(object):
             delay = mdt.now() - now
             delay = delay.seconds * 1E6 + delay.microseconds
 
-            _logger.log(logging.DEBUG, "query: %s", self._obj.query)
+            _logger.debug("query: %s", self._obj.query)
             self.sql_log_count+=1
             res_from = re_from.match(query.lower())
             if res_from:
@@ -254,16 +269,16 @@ class Cursor(object):
             if sqllogs[type]:
                 sqllogitems = sqllogs[type].items()
                 sqllogitems.sort(key=lambda k: k[1][1])
-                _logger.log(logging.DEBUG, "SQL LOG %s:", type)
+                _logger.debug("SQL LOG %s:", type)
                 sqllogitems.sort(lambda x,y: cmp(x[1][0], y[1][0]))
                 for r in sqllogitems:
                     delay = timedelta(microseconds=r[1][1])
-                    _logger.log(logging.DEBUG, "table: %s: %s/%s",
+                    _logger.debug("table: %s: %s/%s",
                                         r[0], delay, r[1][0])
                     sum+= r[1][1]
                 sqllogs[type].clear()
             sum = timedelta(microseconds=sum)
-            _logger.log(logging.DEBUG, "SUM %s:%s/%d [%d]",
+            _logger.debug("SUM %s:%s/%d [%d]",
                                 type, sum, self.sql_log_count, sql_counter)
             sqllogs[type].clear()
         process('from')
@@ -279,6 +294,8 @@ class Cursor(object):
         if not self._obj:
             return
 
+        del self.cache
+
         if self.sql_log:
             self.__closer = frame_codeinfo(currentframe(),3)
         self.print_log()
@@ -380,7 +397,7 @@ class ConnectionPool(object):
         return "ConnectionPool(used=%d/count=%d/max=%d)" % (used, count, self._maxconn)
 
     def _debug(self, msg, *args):
-        _logger.log(logging.DEBUG, ('%r ' + msg), self, *args)
+        _logger.debug(('%r ' + msg), self, *args)
 
     @locked
     def borrow(self, dsn):
@@ -396,7 +413,7 @@ class ConnectionPool(object):
                 delattr(cnx, 'leaked')
                 self._connections.pop(i)
                 self._connections.append((cnx, False))
-                _logger.warn('%r: Free leaked connection to %r', self, cnx.dsn)
+                _logger.warning('%r: Free leaked connection to %r', self, cnx.dsn)
 
         for i, (cnx, used) in enumerate(self._connections):
             if not used and dsn_are_equals(cnx.dsn, dsn):
@@ -461,7 +478,7 @@ class Connection(object):
 
     def cursor(self, serialized=True):
         cursor_type = serialized and 'serialized ' or ''
-        _logger.log(logging.DEBUG, 'create %scursor to %r', cursor_type, self.dbname)
+        _logger.debug('create %scursor to %r', cursor_type, self.dbname)
         return Cursor(self._pool, self.dbname, serialized=serialized)
 
     # serialized_cursor is deprecated - cursors are serialized by default
@@ -504,8 +521,10 @@ def db_connect(db_name):
     return Connection(_Pool, db_name)
 
 def close_db(db_name):
+    global _Pool
     """ You might want to call openerp.modules.registry.RegistryManager.delete(db_name) along this function."""
-    _Pool.close_all(dsn(db_name))
+    if _Pool:
+        _Pool.close_all(dsn(db_name))
     ct = currentThread()
     if hasattr(ct, 'dbname'):
         delattr(ct, 'dbname')