[MERGE] ir_translation: lang field selection only displays installed languages.
[odoo/odoo.git] / openerp / sql_db.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #    Copyright (C) 2010-2011 OpenERP s.a. (<http://openerp.com>).
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU Affero General Public License as
10 #    published by the Free Software Foundation, either version 3 of the
11 #    License, or (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU Affero General Public License for more details.
17 #
18 #    You should have received a copy of the GNU Affero General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 __all__ = ['db_connect', 'close_db']
24
25 from threading import currentThread
26 import logging
27 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT, ISOLATION_LEVEL_READ_COMMITTED, ISOLATION_LEVEL_SERIALIZABLE
28 from psycopg2.psycopg1 import cursor as psycopg1cursor
29 from psycopg2.pool import PoolError
30
31 import psycopg2.extensions
32 import warnings
33
34 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
35
36 types_mapping = {
37     'date': (1082,),
38     'time': (1083,),
39     'datetime': (1114,),
40 }
41
42 def unbuffer(symb, cr):
43     if symb is None: return None
44     return str(symb)
45
46 def undecimalize(symb, cr):
47     if symb is None: return None
48     return float(symb)
49
50 for name, typeoid in types_mapping.items():
51     psycopg2.extensions.register_type(psycopg2.extensions.new_type(typeoid, name, lambda x, cr: x))
52 psycopg2.extensions.register_type(psycopg2.extensions.new_type((700, 701, 1700,), 'float', undecimalize))
53
54
55 import tools
56 from tools.func import wraps, frame_codeinfo
57 from datetime import datetime as mdt
58 from datetime import timedelta
59 import threading
60 from inspect import currentframe
61
62 import re
63 re_from = re.compile('.* from "?([a-zA-Z_0-9]+)"? .*$');
64 re_into = re.compile('.* into "?([a-zA-Z_0-9]+)"? .*$');
65
66 sql_counter = 0
67
68 class Cursor(object):
69     IN_MAX = 1000 # decent limit on size of IN queries - guideline = Oracle limit
70     __logger = None
71
72     def check(f):
73         @wraps(f)
74         def wrapper(self, *args, **kwargs):
75             if self.__closed:
76                 msg = 'Unable to use a closed cursor.'
77                 if self.__closer:
78                     msg += ' It was closed at %s, line %s' % self.__closer
79                 raise psycopg2.OperationalError(msg)
80             return f(self, *args, **kwargs)
81         return wrapper
82
83     def __init__(self, pool, dbname, serialized=False):
84         if self.__class__.__logger is None:
85             self.__class__.__logger = logging.getLogger('db.cursor')
86         self.sql_from_log = {}
87         self.sql_into_log = {}
88
89         # default log level determined at cursor creation, could be
90         # overridden later for debugging purposes
91         self.sql_log = self.__logger.isEnabledFor(logging.DEBUG_SQL)
92
93         self.sql_log_count = 0
94         self.__closed = True    # avoid the call of close() (by __del__) if an exception
95                                 # is raised by any of the following initialisations
96         self._pool = pool
97         self.dbname = dbname
98         self._serialized = serialized
99         self._cnx = pool.borrow(dsn(dbname))
100         self._obj = self._cnx.cursor(cursor_factory=psycopg1cursor)
101         self.__closed = False   # real initialisation value
102         self.autocommit(False)
103         if self.sql_log:
104             self.__caller = frame_codeinfo(currentframe(),2)
105         else:
106             self.__caller = False
107         self.__closer = False
108
109     def __del__(self):
110         if not self.__closed:
111             # Oops. 'self' has not been closed explicitly.
112             # The cursor will be deleted by the garbage collector,
113             # but the database connection is not put back into the connection
114             # pool, preventing some operation on the database like dropping it.
115             # This can also lead to a server overload.
116             msg = "Cursor not closed explicitly\n"
117             if self.__caller:
118                 msg += "Cursor was created at %s:%s" % self.__caller
119             else:
120                 msg += "Please enable sql debugging to trace the caller."
121             self.__logger.warn(msg)
122             self._close(True)
123
124     @check
125     def execute(self, query, params=None, log_exceptions=True):
126         if '%d' in query or '%f' in query:
127             self.__logger.warn(query)
128             self.__logger.warn("SQL queries cannot contain %d or %f anymore. "
129                                "Use only %s")
130
131         if self.sql_log:
132             now = mdt.now()
133
134         try:
135             params = params or None
136             res = self._obj.execute(query, params)
137         except psycopg2.ProgrammingError, pe:
138             if log_exceptions:
139                 self.__logger.error("Programming error: %s, in query %s", pe, query)
140             raise
141         except Exception:
142             if log_exceptions:
143                 self.__logger.exception("bad query: %s", self._obj.query or query)
144             raise
145
146         if self.sql_log:
147             delay = mdt.now() - now
148             delay = delay.seconds * 1E6 + delay.microseconds
149
150             self.__logger.log(logging.DEBUG_SQL, "query: %s", self._obj.query)
151             self.sql_log_count+=1
152             res_from = re_from.match(query.lower())
153             if res_from:
154                 self.sql_from_log.setdefault(res_from.group(1), [0, 0])
155                 self.sql_from_log[res_from.group(1)][0] += 1
156                 self.sql_from_log[res_from.group(1)][1] += delay
157             res_into = re_into.match(query.lower())
158             if res_into:
159                 self.sql_into_log.setdefault(res_into.group(1), [0, 0])
160                 self.sql_into_log[res_into.group(1)][0] += 1
161                 self.sql_into_log[res_into.group(1)][1] += delay
162         return res
163
164
165     def split_for_in_conditions(self, ids):
166         """Split a list of identifiers into one or more smaller tuples
167            safe for IN conditions, after uniquifying them."""
168         return tools.misc.split_every(self.IN_MAX, set(ids))
169
170     def print_log(self):
171         global sql_counter
172         sql_counter += self.sql_log_count
173         if not self.sql_log:
174             return
175         def process(type):
176             sqllogs = {'from':self.sql_from_log, 'into':self.sql_into_log}
177             sum = 0
178             if sqllogs[type]:
179                 sqllogitems = sqllogs[type].items()
180                 sqllogitems.sort(key=lambda k: k[1][1])
181                 self.__logger.log(logging.DEBUG_SQL, "SQL LOG %s:", type)
182                 sqllogitems.sort(lambda x,y: cmp(x[1][0], y[1][0]))
183                 for r in sqllogitems:
184                     delay = timedelta(microseconds=r[1][1])
185                     self.__logger.log(logging.DEBUG_SQL, "table: %s: %s/%s",
186                                         r[0], delay, r[1][0])
187                     sum+= r[1][1]
188                 sqllogs[type].clear()
189             sum = timedelta(microseconds=sum)
190             self.__logger.log(logging.DEBUG_SQL, "SUM %s:%s/%d [%d]",
191                                 type, sum, self.sql_log_count, sql_counter)
192             sqllogs[type].clear()
193         process('from')
194         process('into')
195         self.sql_log_count = 0
196         self.sql_log = False
197
198     @check
199     def close(self):
200         return self._close(False)
201
202     def _close(self, leak=False):
203         if not self._obj:
204             return
205
206         if self.sql_log:
207             self.__closer = frame_codeinfo(currentframe(),3)
208         self.print_log()
209
210         if not self._serialized:
211             self.rollback() # Ensure we close the current transaction.
212
213         self._obj.close()
214
215         # This force the cursor to be freed, and thus, available again. It is
216         # important because otherwise we can overload the server very easily
217         # because of a cursor shortage (because cursors are not garbage
218         # collected as fast as they should). The problem is probably due in
219         # part because browse records keep a reference to the cursor.
220         del self._obj
221         self.__closed = True
222
223         if leak:
224             self._cnx.leaked = True
225         else:
226             keep_in_pool = self.dbname not in ('template1', 'template0', 'postgres')
227             self._pool.give_back(self._cnx, keep_in_pool=keep_in_pool)
228
229     @check
230     def autocommit(self, on):
231         offlevel = [ISOLATION_LEVEL_READ_COMMITTED, ISOLATION_LEVEL_SERIALIZABLE][bool(self._serialized)]
232         self._cnx.set_isolation_level([offlevel, ISOLATION_LEVEL_AUTOCOMMIT][bool(on)])
233
234     @check
235     def commit(self):
236         return self._cnx.commit()
237
238     @check
239     def rollback(self):
240         return self._cnx.rollback()
241
242     @check
243     def __getattr__(self, name):
244         return getattr(self._obj, name)
245
246
247 class PsycoConnection(psycopg2.extensions.connection):
248     pass
249
250 class ConnectionPool(object):
251
252     __logger = logging.getLogger('db.connection_pool')
253
254     def locked(fun):
255         @wraps(fun)
256         def _locked(self, *args, **kwargs):
257             self._lock.acquire()
258             try:
259                 return fun(self, *args, **kwargs)
260             finally:
261                 self._lock.release()
262         return _locked
263
264
265     def __init__(self, maxconn=64):
266         self._connections = []
267         self._maxconn = max(maxconn, 1)
268         self._lock = threading.Lock()
269
270     def __repr__(self):
271         used = len([1 for c, u in self._connections[:] if u])
272         count = len(self._connections)
273         return "ConnectionPool(used=%d/count=%d/max=%d)" % (used, count, self._maxconn)
274
275     def _debug(self, msg, *args):
276         self.__logger.log(logging.DEBUG_SQL, ('%r ' + msg), self, *args)
277
278     @locked
279     def borrow(self, dsn):
280         self._debug('Borrow connection to %r', dsn)
281
282         # free leaked connections
283         for i, (cnx, _) in tools.reverse_enumerate(self._connections):
284             if getattr(cnx, 'leaked', False):
285                 delattr(cnx, 'leaked')
286                 self._connections.pop(i)
287                 self._connections.append((cnx, False))
288                 self.__logger.warn('%r: Free leaked connection to %r', self, cnx.dsn)
289
290         for i, (cnx, used) in enumerate(self._connections):
291             if not used and dsn_are_equals(cnx.dsn, dsn):
292                 self._connections.pop(i)
293                 self._connections.append((cnx, True))
294                 self._debug('Existing connection found at index %d', i)
295
296                 return cnx
297
298         if len(self._connections) >= self._maxconn:
299             # try to remove the oldest connection not used
300             for i, (cnx, used) in enumerate(self._connections):
301                 if not used:
302                     self._connections.pop(i)
303                     self._debug('Removing old connection at index %d: %r', i, cnx.dsn)
304                     break
305             else:
306                 # note: this code is called only if the for loop has completed (no break)
307                 raise PoolError('The Connection Pool Is Full')
308
309         try:
310             result = psycopg2.connect(dsn=dsn, connection_factory=PsycoConnection)
311         except psycopg2.Error, e:
312             self.__logger.exception('Connection to the database failed')
313             raise
314         self._connections.append((result, True))
315         self._debug('Create new connection')
316         return result
317
318     @locked
319     def give_back(self, connection, keep_in_pool=True):
320         self._debug('Give back connection to %r', connection.dsn)
321         for i, (cnx, used) in enumerate(self._connections):
322             if cnx is connection:
323                 self._connections.pop(i)
324                 if keep_in_pool:
325                     self._connections.append((cnx, False))
326                     self._debug('Put connection to %r in pool', cnx.dsn)
327                 else:
328                     self._debug('Forgot connection to %r', cnx.dsn)
329                 break
330         else:
331             raise PoolError('This connection does not below to the pool')
332
333     @locked
334     def close_all(self, dsn):
335         self.__logger.info('%r: Close all connections to %r', self, dsn)
336         for i, (cnx, used) in tools.reverse_enumerate(self._connections):
337             if dsn_are_equals(cnx.dsn, dsn):
338                 cnx.close()
339                 self._connections.pop(i)
340
341
342 class Connection(object):
343     __logger = logging.getLogger('db.connection')
344
345     def __init__(self, pool, dbname):
346         self.dbname = dbname
347         self._pool = pool
348
349     def cursor(self, serialized=False):
350         cursor_type = serialized and 'serialized ' or ''
351         self.__logger.log(logging.DEBUG_SQL, 'create %scursor to %r', cursor_type, self.dbname)
352         return Cursor(self._pool, self.dbname, serialized=serialized)
353
354     def serialized_cursor(self):
355         return self.cursor(True)
356
357     def __nonzero__(self):
358         """Check if connection is possible"""
359         try:
360             warnings.warn("You use an expensive function to test a connection.",
361                       DeprecationWarning, stacklevel=1)
362             cr = self.cursor()
363             cr.close()
364             return True
365         except Exception:
366             return False
367
368 def dsn(db_name):
369     _dsn = ''
370     for p in ('host', 'port', 'user', 'password'):
371         cfg = tools.config['db_' + p]
372         if cfg:
373             _dsn += '%s=%s ' % (p, cfg)
374
375     return '%sdbname=%s' % (_dsn, db_name)
376
377 def dsn_are_equals(first, second):
378     def key(dsn):
379         k = dict(x.split('=', 1) for x in dsn.strip().split())
380         k.pop('password', None) # password is not relevant
381         return k
382     return key(first) == key(second)
383
384
385 _Pool = None
386
387 def db_connect(db_name):
388     global _Pool
389     if _Pool is None:
390         _Pool = ConnectionPool(int(tools.config['db_maxconn']))
391     currentThread().dbname = db_name
392     return Connection(_Pool, db_name)
393
394 def close_db(db_name):
395     """ You might want to call openerp.netsvc.Agent.cancel(db_name) along this function."""
396     _Pool.close_all(dsn(db_name))
397     tools.cache.clean_caches_for_db(db_name)
398     ct = currentThread()
399     if hasattr(ct, 'dbname'):
400         delattr(ct, 'dbname')
401
402
403 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
404