1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
23 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT, ISOLATION_LEVEL_READ_COMMITTED, ISOLATION_LEVEL_SERIALIZABLE
24 from psycopg2.pool import ThreadedConnectionPool
25 from psycopg2.psycopg1 import cursor as psycopg1cursor
27 import psycopg2.extensions
29 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
37 def unbuffer(symb, cr):
38 if symb is None: return None
41 def undecimalize(symb, cr):
42 if symb is None: return None
45 for name, typeoid in types_mapping.items():
46 psycopg2.extensions.register_type(psycopg2.extensions.new_type(typeoid, name, lambda x, cr: x))
47 psycopg2.extensions.register_type(psycopg2.extensions.new_type((700, 701, 1700,), 'float', undecimalize))
53 from mx import DateTime as mdt
54 re_from = re.compile('.* from "?([a-zA-Z_0-9]+)"? .*$');
55 re_into = re.compile('.* into "?([a-zA-Z_0-9]+)"? .*$');
57 def log(msg, lvl=netsvc.LOG_DEBUG):
58 logger = netsvc.Logger()
59 logger.notifyChannel('sql', lvl, msg)
69 from tools.func import wraps
72 def wrapper(self, *args, **kwargs):
74 raise psycopg2.ProgrammingError('Unable to use the cursor after having closing it')
75 return f(self, *args, **kwargs)
78 def __init__(self, pool, serialized=False):
80 self._serialized = serialized
81 self._cnx = pool.getconn()
82 self._obj = self._cnx.cursor(cursor_factory=psycopg1cursor)
84 self.autocommit(False)
85 self.dbname = pool.dbname
87 if tools.config['log_level'] in (netsvc.LOG_DEBUG, netsvc.LOG_DEBUG_RPC):
88 from inspect import stack
89 self.__caller = tuple(stack()[2][1:3])
93 if tools.config['log_level'] in (netsvc.LOG_DEBUG, netsvc.LOG_DEBUG_RPC):
94 # Oops. 'self' has not been closed explicitly.
95 # The cursor will be deleted by the garbage collector,
96 # but the database connection is not put back into the connection
97 # pool, preventing some operation on the database like dropping it.
98 # This can also lead to a server overload.
99 msg = "Cursor not closed explicitly\n" \
100 "Cursor was created at %s:%s" % self.__caller
102 log(msg, netsvc.LOG_WARNING)
106 def execute(self, query, params=None):
108 if '%d' in query or '%f' in query:
109 log(query, netsvc.LOG_WARNING)
110 log("SQL queries mustn't contain %d or %f anymore. Use only %s", netsvc.LOG_WARNING)
112 query = query.replace('%d', '%s').replace('%f', '%s')
118 params = params or None
119 res = self._obj.execute(query, params)
121 log("bad query: %s" % self._obj.query)
126 log("query: %s" % self._obj.query)
128 res_from = re_from.match(query.lower())
130 self.sql_from_log.setdefault(res_from.group(1), [0, 0])
131 self.sql_from_log[res_from.group(1)][0] += 1
132 self.sql_from_log[res_from.group(1)][1] += mdt.now() - now
133 res_into = re_into.match(query.lower())
135 self.sql_into_log.setdefault(res_into.group(1), [0, 0])
136 self.sql_into_log[res_into.group(1)][0] += 1
137 self.sql_into_log[res_into.group(1)][1] += mdt.now() - now
142 sqllogs = {'from':self.sql_from_log, 'into':self.sql_into_log}
143 if not sqllogs[type]:
145 sqllogitems = sqllogs[type].items()
146 sqllogitems.sort(key=lambda k: k[1][1])
148 log("SQL LOG %s:" % (type,))
149 for r in sqllogitems:
150 log("table: %s: %s/%s" %(r[0], str(r[1][1]), r[1][0]))
152 log("SUM:%s/%d" % (sum, self.count))
153 sqllogs[type].clear()
161 self.rollback() # Ensure we close the current transaction.
165 # This force the cursor to be freed, and thus, available again. It is
166 # important because otherwise we can overload the server very easily
167 # because of a cursor shortage (because cursors are not garbage
168 # collected as fast as they should). The problem is probably due in
169 # part because browse records keep a reference to the cursor.
172 self._pool.putconn(self._cnx)
175 def autocommit(self, on):
176 offlevel = [ISOLATION_LEVEL_READ_COMMITTED, ISOLATION_LEVEL_SERIALIZABLE][bool(self._serialized)]
177 self._cnx.set_isolation_level([offlevel, ISOLATION_LEVEL_AUTOCOMMIT][bool(on)])
181 return self._cnx.commit()
185 return self._cnx.rollback()
188 def __getattr__(self, name):
189 return getattr(self._obj, name)
191 class ConnectionPool(object):
192 def __init__(self, pool, dbname):
199 def serialized_cursor(self):
200 return Cursor(self, True)
202 def __getattr__(self, name):
203 return getattr(self._pool, name)
205 class PoolManager(object):
208 maxconn = int(tools.config['db_maxconn']) or 64
211 def dsn(cls, db_name):
214 for p in ('host', 'port', 'user', 'password'):
215 cfg = tools.config['db_' + p]
217 cls._dsn += '%s=%s ' % (p, cfg)
218 return '%s dbname=%s' % (cls._dsn, db_name)
221 def get(cls, db_name):
222 if db_name not in cls._pools:
223 logger = netsvc.Logger()
225 logger.notifyChannel('dbpool', netsvc.LOG_INFO, 'Connecting to %s' % (db_name,))
226 cls._pools[db_name] = ConnectionPool(ThreadedConnectionPool(1, cls.maxconn, cls.dsn(db_name)), db_name)
228 logger.notifyChannel('dbpool', netsvc.LOG_ERROR, 'Unable to connect to %s: %s' %
231 return cls._pools[db_name]
234 def close(cls, db_name):
235 if db_name in cls._pools:
236 logger = netsvc.Logger()
237 logger.notifyChannel('dbpool', netsvc.LOG_INFO, 'Closing all connections to %s' % (db_name,))
238 cls._pools[db_name].closeall()
239 del cls._pools[db_name]
241 def db_connect(db_name):
242 return PoolManager.get(db_name)
244 def close_db(db_name):
245 PoolManager.close(db_name)
246 tools.cache.clean_caches_for_db(db_name)
249 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: