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 #.apidoc title: PostgreSQL interface
26 The PostgreSQL connector is a connectivity layer between the OpenERP code and
27 the database, *not* a database abstraction toolkit. Database abstraction is what
28 the ORM does, in fact.
30 See also: the `pooler` module
33 #.apidoc add-functions: print_stats
34 #.apidoc add-classes: Cursor Connection ConnectionPool
36 __all__ = ['db_connect', 'close_db']
38 from threading import currentThread
40 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT, ISOLATION_LEVEL_READ_COMMITTED, ISOLATION_LEVEL_SERIALIZABLE
41 from psycopg2.psycopg1 import cursor as psycopg1cursor
42 from psycopg2.pool import PoolError
44 import psycopg2.extensions
47 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
55 def unbuffer(symb, cr):
56 if symb is None: return None
59 def undecimalize(symb, cr):
60 if symb is None: return None
63 for name, typeoid in types_mapping.items():
64 psycopg2.extensions.register_type(psycopg2.extensions.new_type(typeoid, name, lambda x, cr: x))
65 psycopg2.extensions.register_type(psycopg2.extensions.new_type((700, 701, 1700,), 'float', undecimalize))
69 from tools.func import wraps, frame_codeinfo
70 from datetime import datetime as mdt
71 from datetime import timedelta
73 from inspect import currentframe
76 re_from = re.compile('.* from "?([a-zA-Z_0-9]+)"? .*$');
77 re_into = re.compile('.* into "?([a-zA-Z_0-9]+)"? .*$');
82 """ Cursor is an open transaction to Postgres, utilizing a TCP connection
84 A lightweight wrapper around psycopg2's `psycopg1cursor` objects
86 This is the object behind the `cr` variable used all over the OpenERP
89 IN_MAX = 1000 # decent limit on size of IN queries - guideline = Oracle limit
94 def wrapper(self, *args, **kwargs):
96 msg = 'Unable to use a closed cursor.'
98 msg += ' It was closed at %s, line %s' % self.__closer
99 raise psycopg2.OperationalError(msg)
100 return f(self, *args, **kwargs)
103 def __init__(self, pool, dbname, serialized=False):
104 if self.__class__.__logger is None:
105 self.__class__.__logger = logging.getLogger('db.cursor')
106 self.sql_from_log = {}
107 self.sql_into_log = {}
109 # default log level determined at cursor creation, could be
110 # overridden later for debugging purposes
111 self.sql_log = self.__logger.isEnabledFor(logging.DEBUG_SQL)
113 self.sql_log_count = 0
114 self.__closed = True # avoid the call of close() (by __del__) if an exception
115 # is raised by any of the following initialisations
118 self._serialized = serialized
119 self._cnx = pool.borrow(dsn(dbname))
120 self._obj = self._cnx.cursor(cursor_factory=psycopg1cursor)
121 self.__closed = False # real initialisation value
122 self.autocommit(False)
124 self.__caller = frame_codeinfo(currentframe(),2)
126 self.__caller = False
127 self.__closer = False
130 if not self.__closed:
131 # Oops. 'self' has not been closed explicitly.
132 # The cursor will be deleted by the garbage collector,
133 # but the database connection is not put back into the connection
134 # pool, preventing some operation on the database like dropping it.
135 # This can also lead to a server overload.
136 msg = "Cursor not closed explicitly\n"
138 msg += "Cursor was created at %s:%s" % self.__caller
140 msg += "Please enable sql debugging to trace the caller."
141 self.__logger.warn(msg)
145 def execute(self, query, params=None, log_exceptions=True):
146 if '%d' in query or '%f' in query:
147 self.__logger.warn(query)
148 self.__logger.warn("SQL queries cannot contain %d or %f anymore. "
155 params = params or None
156 res = self._obj.execute(query, params)
157 except psycopg2.ProgrammingError, pe:
159 self.__logger.error("Programming error: %s, in query %s", pe, query)
163 self.__logger.exception("bad query: %s", self._obj.query or query)
167 delay = mdt.now() - now
168 delay = delay.seconds * 1E6 + delay.microseconds
170 self.__logger.log(logging.DEBUG_SQL, "query: %s", self._obj.query)
171 self.sql_log_count+=1
172 res_from = re_from.match(query.lower())
174 self.sql_from_log.setdefault(res_from.group(1), [0, 0])
175 self.sql_from_log[res_from.group(1)][0] += 1
176 self.sql_from_log[res_from.group(1)][1] += delay
177 res_into = re_into.match(query.lower())
179 self.sql_into_log.setdefault(res_into.group(1), [0, 0])
180 self.sql_into_log[res_into.group(1)][0] += 1
181 self.sql_into_log[res_into.group(1)][1] += delay
185 def split_for_in_conditions(self, ids):
186 """Split a list of identifiers into one or more smaller tuples
187 safe for IN conditions, after uniquifying them."""
188 return tools.misc.split_every(self.IN_MAX, set(ids))
192 sql_counter += self.sql_log_count
196 sqllogs = {'from':self.sql_from_log, 'into':self.sql_into_log}
199 sqllogitems = sqllogs[type].items()
200 sqllogitems.sort(key=lambda k: k[1][1])
201 self.__logger.log(logging.DEBUG_SQL, "SQL LOG %s:", type)
202 sqllogitems.sort(lambda x,y: cmp(x[1][0], y[1][0]))
203 for r in sqllogitems:
204 delay = timedelta(microseconds=r[1][1])
205 self.__logger.log(logging.DEBUG_SQL, "table: %s: %s/%s",
206 r[0], delay, r[1][0])
208 sqllogs[type].clear()
209 sum = timedelta(microseconds=sum)
210 self.__logger.log(logging.DEBUG_SQL, "SUM %s:%s/%d [%d]",
211 type, sum, self.sql_log_count, sql_counter)
212 sqllogs[type].clear()
215 self.sql_log_count = 0
220 return self._close(False)
222 def _close(self, leak=False):
227 self.__closer = frame_codeinfo(currentframe(),3)
230 if not self._serialized:
231 self.rollback() # Ensure we close the current transaction.
235 # This force the cursor to be freed, and thus, available again. It is
236 # important because otherwise we can overload the server very easily
237 # because of a cursor shortage (because cursors are not garbage
238 # collected as fast as they should). The problem is probably due in
239 # part because browse records keep a reference to the cursor.
244 self._cnx.leaked = True
246 keep_in_pool = self.dbname not in ('template1', 'template0', 'postgres')
247 self._pool.give_back(self._cnx, keep_in_pool=keep_in_pool)
250 def autocommit(self, on):
251 offlevel = [ISOLATION_LEVEL_READ_COMMITTED, ISOLATION_LEVEL_SERIALIZABLE][bool(self._serialized)]
252 self._cnx.set_isolation_level([offlevel, ISOLATION_LEVEL_AUTOCOMMIT][bool(on)])
256 """ Perform an SQL `COMMIT`
258 return self._cnx.commit()
262 """ Perform an SQL `ROLLBACK`
264 return self._cnx.rollback()
267 def __getattr__(self, name):
268 return getattr(self._obj, name)
270 """ Set the mode of postgres operations for all cursors
272 """Obtain the mode of postgres operations for all cursors
275 class PsycoConnection(psycopg2.extensions.connection):
278 class ConnectionPool(object):
279 """ The pool of connections to database(s)
281 Keep a set of connections to pg databases open, and reuse them
282 to open cursors for all transactions.
284 The connections are *not* automatically closed. Only a close_db()
287 __logger = logging.getLogger('db.connection_pool')
291 def _locked(self, *args, **kwargs):
294 return fun(self, *args, **kwargs)
300 def __init__(self, maxconn=64):
301 self._connections = []
302 self._maxconn = max(maxconn, 1)
303 self._lock = threading.Lock()
306 used = len([1 for c, u in self._connections[:] if u])
307 count = len(self._connections)
308 return "ConnectionPool(used=%d/count=%d/max=%d)" % (used, count, self._maxconn)
310 def _debug(self, msg, *args):
311 self.__logger.log(logging.DEBUG_SQL, ('%r ' + msg), self, *args)
314 def borrow(self, dsn):
315 self._debug('Borrow connection to %r', dsn)
317 # free leaked connections
318 for i, (cnx, _) in tools.reverse_enumerate(self._connections):
319 if getattr(cnx, 'leaked', False):
320 delattr(cnx, 'leaked')
321 self._connections.pop(i)
322 self._connections.append((cnx, False))
323 self.__logger.warn('%r: Free leaked connection to %r', self, cnx.dsn)
325 for i, (cnx, used) in enumerate(self._connections):
326 if not used and dsn_are_equals(cnx.dsn, dsn):
327 self._connections.pop(i)
328 self._connections.append((cnx, True))
329 self._debug('Existing connection found at index %d', i)
333 if len(self._connections) >= self._maxconn:
334 # try to remove the oldest connection not used
335 for i, (cnx, used) in enumerate(self._connections):
337 self._connections.pop(i)
338 self._debug('Removing old connection at index %d: %r', i, cnx.dsn)
341 # note: this code is called only if the for loop has completed (no break)
342 raise PoolError('The Connection Pool Is Full')
345 result = psycopg2.connect(dsn=dsn, connection_factory=PsycoConnection)
346 except psycopg2.Error, e:
347 self.__logger.exception('Connection to the database failed')
349 self._connections.append((result, True))
350 self._debug('Create new connection')
354 def give_back(self, connection, keep_in_pool=True):
355 self._debug('Give back connection to %r', connection.dsn)
356 for i, (cnx, used) in enumerate(self._connections):
357 if cnx is connection:
358 self._connections.pop(i)
360 self._connections.append((cnx, False))
361 self._debug('Put connection to %r in pool', cnx.dsn)
363 self._debug('Forgot connection to %r', cnx.dsn)
366 raise PoolError('This connection does not below to the pool')
369 def close_all(self, dsn):
370 self.__logger.info('%r: Close all connections to %r', self, dsn)
371 for i, (cnx, used) in tools.reverse_enumerate(self._connections):
372 if dsn_are_equals(cnx.dsn, dsn):
374 self._connections.pop(i)
377 class Connection(object):
378 """ A lightweight instance of a connection to postgres
380 __logger = logging.getLogger('db.connection')
382 def __init__(self, pool, dbname):
386 def cursor(self, serialized=False):
387 cursor_type = serialized and 'serialized ' or ''
388 self.__logger.log(logging.DEBUG_SQL, 'create %scursor to %r', cursor_type, self.dbname)
389 return Cursor(self._pool, self.dbname, serialized=serialized)
391 def serialized_cursor(self):
392 return self.cursor(True)
394 def __nonzero__(self):
395 """Check if connection is possible"""
397 warnings.warn("You use an expensive function to test a connection.",
398 DeprecationWarning, stacklevel=1)
407 for p in ('host', 'port', 'user', 'password'):
408 cfg = tools.config['db_' + p]
410 _dsn += '%s=%s ' % (p, cfg)
412 return '%sdbname=%s' % (_dsn, db_name)
414 def dsn_are_equals(first, second):
416 k = dict(x.split('=', 1) for x in dsn.strip().split())
417 k.pop('password', None) # password is not relevant
419 return key(first) == key(second)
424 def db_connect(db_name):
427 _Pool = ConnectionPool(int(tools.config['db_maxconn']))
428 currentThread().dbname = db_name
429 return Connection(_Pool, db_name)
431 def close_db(db_name):
432 """ You might want to call openerp.netsvc.Agent.cancel(db_name) along this function."""
433 _Pool.close_all(dsn(db_name))
434 tools.cache.clean_caches_for_db(db_name)
436 if hasattr(ct, 'dbname'):
437 delattr(ct, 'dbname')
440 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: