1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (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 General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ##############################################################################
24 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT, ISOLATION_LEVEL_SERIALIZABLE
25 from psycopg2.pool import ThreadedConnectionPool
26 from psycopg2.psycopg1 import cursor as psycopg1cursor
28 import psycopg2.extensions
30 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
38 def unbuffer(symb, cr):
39 if symb is None: return None
42 def undecimalize(symb, cr):
43 if symb is None: return None
46 for name, typeoid in types_mapping.items():
47 psycopg2.extensions.register_type(psycopg2.extensions.new_type(typeoid, name, lambda x, cr: x))
48 psycopg2.extensions.register_type(psycopg2.extensions.new_type((700, 701, 1700,), 'float', undecimalize))
54 from mx import DateTime as mdt
55 re_from = re.compile('.* from "?([a-zA-Z_0-9]+)"? .*$');
56 re_into = re.compile('.* into "?([a-zA-Z_0-9]+)"? .*$');
58 def log(msg, lvl=netsvc.LOG_DEBUG):
59 logger = netsvc.Logger()
60 logger.notifyChannel('sql', lvl, msg)
70 from tools.func import wraps
73 def wrapper(self, *args, **kwargs):
74 if not hasattr(self, '_obj'):
75 raise psycopg2.ProgrammingError('Unable to use the cursor after having closing it')
76 return f(self, *args, **kwargs)
79 def __init__(self, pool):
81 self._cnx = pool.getconn()
82 self._obj = self._cnx.cursor(cursor_factory=psycopg1cursor)
83 self.autocommit(False)
84 self.dbname = pool.dbname
86 if tools.config['log_level'] in (netsvc.LOG_DEBUG, netsvc.LOG_DEBUG_RPC):
87 from inspect import stack
88 self.__caller = tuple(stack()[2][1:3])
91 if hasattr(self, '_obj'):
92 if tools.config['log_level'] in (netsvc.LOG_DEBUG, netsvc.LOG_DEBUG_RPC):
93 # Oops. 'self' has not been closed explicitly.
94 # The cursor will be deleted by the garbage collector,
95 # but the database connection is not put back into the connection
96 # pool, preventing some operation on the database like dropping it.
97 # This can also lead to a server overload.
98 msg = "Cursor not closed explicitly\n" \
99 "Cursor was created at %s:%s" % self.__caller
101 log(msg, netsvc.LOG_WARNING)
105 def execute(self, query, params=None):
107 if '%d' in query or '%f' in query:
108 log(query, netsvc.LOG_WARNING)
109 log("SQL queries mustn't containt %d or %f anymore. Use only %s", netsvc.LOG_WARNING)
111 query = query.replace('%d', '%s').replace('%f', '%s')
116 res = self._obj.execute(query, params)
119 log("query: %s" % self._obj.query)
121 res_from = re_from.match(query.lower())
123 self.sql_from_log.setdefault(res_from.group(1), [0, 0])
124 self.sql_from_log[res_from.group(1)][0] += 1
125 self.sql_from_log[res_from.group(1)][1] += mdt.now() - now
126 res_into = re_into.match(query.lower())
128 self.sql_into_log.setdefault(res_into.group(1), [0, 0])
129 self.sql_into_log[res_into.group(1)][0] += 1
130 self.sql_into_log[res_into.group(1)][1] += mdt.now() - now
135 sqllogs = {'from':self.sql_from_log, 'into':self.sql_into_log}
136 if not sqllogs[type]:
138 sqllogitems = sqllogs[type].items()
139 sqllogitems.sort(key=lambda k: k[1][1])
141 log("SQL LOG %s:" % (type,))
142 for r in sqllogitems:
143 log("table: %s: %s/%s" %(r[0], str(r[1][1]), r[1][0]))
145 log("SUM:%s/%d" % (sum, self.count))
146 sqllogs[type].clear()
157 # This force the cursor to be freed, and thus, available again. It is
158 # important because otherwise we can overload the server very easily
159 # because of a cursor shortage (because cursors are not garbage
160 # collected as fast as they should). The problem is probably due in
161 # part because browse records keep a reference to the cursor.
163 self._pool.putconn(self._cnx)
166 def autocommit(self, on):
167 self._cnx.set_isolation_level([ISOLATION_LEVEL_SERIALIZABLE, ISOLATION_LEVEL_AUTOCOMMIT][bool(on)])
171 return self._cnx.commit()
175 return self._cnx.rollback()
178 def __getattr__(self, name):
179 return getattr(self._obj, name)
181 class ConnectionPool(object):
182 def __init__(self, pool, dbname):
189 def __getattr__(self, name):
190 return getattr(self._pool, name)
192 class PoolManager(object):
195 maxconn = int(tools.config['db_maxconn']) or 64
198 def dsn(cls, db_name):
201 for p in ('host', 'port', 'user', 'password'):
202 cfg = tools.config['db_' + p]
204 cls._dsn += '%s=%s ' % (p, cfg)
205 return '%s dbname=%s' % (cls._dsn, db_name)
208 def get(cls, db_name):
209 if db_name not in cls._pools:
210 logger = netsvc.Logger()
212 logger.notifyChannel('dbpool', netsvc.LOG_INFO, 'Connecting to %s' % (db_name,))
213 cls._pools[db_name] = ConnectionPool(ThreadedConnectionPool(1, cls.maxconn, cls.dsn(db_name)), db_name)
215 logger.notifyChannel('dbpool', netsvc.LOG_ERROR, 'Unable to connect to %s: %s' %
218 return cls._pools[db_name]
221 def close(cls, db_name):
222 if db_name in cls._pools:
223 logger = netsvc.Logger()
224 logger.notifyChannel('dbpool', netsvc.LOG_INFO, 'Closing all connections to %s' % (db_name,))
225 cls._pools[db_name].closeall()
226 del cls._pools[db_name]
228 def db_connect(db_name):
229 return PoolManager.get(db_name)
231 def close_db(db_name):
232 PoolManager.close(db_name)
233 tools.cache.clean_caches_for_db(db_name)
236 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: