1
2
3
4
5
6
7
8
9
10
11
12
13 import MySQLdb
14 import MySQLdb.converters
15 from MySQLdb.constants import FIELD_TYPE
16
17 import time
18 import DateTime
19
20 from Queue import Queue, Empty, Full
21
22 import logging
23 log = logging.getLogger("zen.DbConnectionPool")
24
25 POOL_SIZE = 5
26 KEEP_ALIVE = 28800
27
29
31 if not '_the_instance' in type.__dict__:
32 type._the_instance = object.__new__(type)
33 return type._the_instance
34
35 '''
36 instance = None
37 def __new__(cls, *args, **kargs):
38 if cls.instance is None:
39 cls.instance = object.__new__(cls, *args, **kargs)
40 log.debug('Returning single instance of DbConnectionPool')
41 return cls.instance
42 '''
43
46
49 try:
50 putstamp,obj = Queue.get(self, block)
51
52 if time.time() - putstamp >= KEEP_ALIVE:
53 log.debug('Retrieved a stale connection; Pool size: %s' % self.qsize())
54 obj.close()
55 return self._createConnection(host=host, port=port,
56 username=username,
57 password=password,
58 database=database)
59 else:
60 log.debug('Retrieved a connection; Pool size: %s' % self.qsize())
61 if hasattr(obj, 'ping'):
62
63 obj.ping()
64 return obj
65
66 except Empty:
67 return self._createConnection(host=host, port=port,
68 username=username,
69 password=password,
70 database=database)
71
72 - def put(self, obj, block=0):
73 try:
74 Queue.put(self, (time.time(),obj), block)
75 log.debug('Returned a connection; Pool size: %s' % self.qsize())
76 except Full:
77 pass
78
81 log.debug('Creating a new connection; Pool size: %s' % self.qsize())
82 conn = None
83 """
84 if self.backend == "omnibus":
85 import Sybase
86 self.conn = Sybase.connect(self.database,self.username,
87 self.password)
88 elif self.backend == "oracle":
89 import DCOracle2
90 connstr = "%s/%s@%s" % (self.username, self.password, self.database)
91 self.conn = DCOracle2.connect(connstr)
92 elif self.backend == "mysql":
93 """
94 mysqlconv = MySQLdb.converters.conversions.copy()
95 mysqlconv[FIELD_TYPE.DATETIME] = DateTime.DateTime
96 mysqlconv[FIELD_TYPE.TIMESTAMP] = DateTime.DateTime
97
98 mysqlconv[FIELD_TYPE.LONG] = int
99 if not host:
100 host, database = database, 'events'
101 conn = MySQLdb.connect(host=host, user=username,
102 port=port, passwd=password,
103 db=database, conv=mysqlconv, reconnect=1)
104 conn.autocommit(1)
105 return conn
106