1 # -*- coding: utf-8 -*-
2 ##############################################################################
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>).
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.
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.
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/>.
21 ##############################################################################
23 __all__ = ['db_connect', 'close_db']
25 from threading import currentThread
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
31 import psycopg2.extensions
34 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
42 def unbuffer(symb, cr):
43 if symb is None: return None
46 def undecimalize(symb, cr):
47 if symb is None: return None
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))
56 from tools.func import wraps, frame_codeinfo
57 from datetime import datetime as mdt
58 from datetime import timedelta
60 from inspect import currentframe
63 re_from = re.compile('.* from "?([a-zA-Z_0-9]+)"? .*$');
64 re_into = re.compile('.* into "?([a-zA-Z_0-9]+)"? .*$');
69 IN_MAX = 1000 # decent limit on size of IN queries - guideline = Oracle limit
74 def wrapper(self, *args, **kwargs):
76 msg = 'Unable to use a closed cursor.'
78 msg += ' It was closed at %s, line %s' % self.__closer
79 raise psycopg2.OperationalError(msg)
80 return f(self, *args, **kwargs)
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 = {}
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)
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
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)
104 self.__caller = frame_codeinfo(currentframe(),2)
106 self.__caller = False
107 self.__closer = False
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"
118 msg += "Cursor was created at %s:%s" % self.__caller
120 msg += "Please enable sql debugging to trace the caller."
121 self.__logger.warn(msg)
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. "
135 params = params or None
136 res = self._obj.execute(query, params)
137 except psycopg2.ProgrammingError, pe:
139 self.__logger.error("Programming error: %s, in query %s", pe, query)
143 self.__logger.exception("bad query: %s", self._obj.query or query)
147 delay = mdt.now() - now
148 delay = delay.seconds * 1E6 + delay.microseconds
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())
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())
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
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))
172 sql_counter += self.sql_log_count
176 sqllogs = {'from':self.sql_from_log, 'into':self.sql_into_log}
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])
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()
195 self.sql_log_count = 0
200 return self._close(False)
202 def _close(self, leak=False):
207 self.__closer = frame_codeinfo(currentframe(),3)
210 if not self._serialized:
211 self.rollback() # Ensure we close the current transaction.
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.
224 self._cnx.leaked = True
226 keep_in_pool = self.dbname not in ('template1', 'template0', 'postgres')
227 self._pool.give_back(self._cnx, keep_in_pool=keep_in_pool)
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)])
236 return self._cnx.commit()
240 return self._cnx.rollback()
243 def __getattr__(self, name):
244 return getattr(self._obj, name)
247 class PsycoConnection(psycopg2.extensions.connection):
250 class ConnectionPool(object):
252 __logger = logging.getLogger('db.connection_pool')
256 def _locked(self, *args, **kwargs):
259 return fun(self, *args, **kwargs)
265 def __init__(self, maxconn=64):
266 self._connections = []
267 self._maxconn = max(maxconn, 1)
268 self._lock = threading.Lock()
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)
275 def _debug(self, msg, *args):
276 self.__logger.log(logging.DEBUG_SQL, ('%r ' + msg), self, *args)
279 def borrow(self, dsn):
280 self._debug('Borrow connection to %r', dsn)
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)
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)
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):
302 self._connections.pop(i)
303 self._debug('Removing old connection at index %d: %r', i, cnx.dsn)
306 # note: this code is called only if the for loop has completed (no break)
307 raise PoolError('The Connection Pool Is Full')
310 result = psycopg2.connect(dsn=dsn, connection_factory=PsycoConnection)
311 except psycopg2.Error, e:
312 self.__logger.exception('Connection to the database failed')
314 self._connections.append((result, True))
315 self._debug('Create new connection')
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)
325 self._connections.append((cnx, False))
326 self._debug('Put connection to %r in pool', cnx.dsn)
328 self._debug('Forgot connection to %r', cnx.dsn)
331 raise PoolError('This connection does not below to the pool')
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):
339 self._connections.pop(i)
342 class Connection(object):
343 __logger = logging.getLogger('db.connection')
345 def __init__(self, pool, dbname):
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)
354 def serialized_cursor(self):
355 return self.cursor(True)
357 def __nonzero__(self):
358 """Check if connection is possible"""
360 warnings.warn("You use an expensive function to test a connection.",
361 DeprecationWarning, stacklevel=1)
370 for p in ('host', 'port', 'user', 'password'):
371 cfg = tools.config['db_' + p]
373 _dsn += '%s=%s ' % (p, cfg)
375 return '%sdbname=%s' % (_dsn, db_name)
377 def dsn_are_equals(first, second):
379 k = dict(x.split('=', 1) for x in dsn.strip().split())
380 k.pop('password', None) # password is not relevant
382 return key(first) == key(second)
387 def db_connect(db_name):
390 _Pool = ConnectionPool(int(tools.config['db_maxconn']))
391 currentThread().dbname = db_name
392 return Connection(_Pool, db_name)
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)
399 if hasattr(ct, 'dbname'):
400 delattr(ct, 'dbname')
403 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: