-
Notifications
You must be signed in to change notification settings - Fork 5
/
poolmysql.py
282 lines (205 loc) · 6.24 KB
/
poolmysql.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import MySQLdb
from datetime import datetime, timedelta
from contextlib import contextmanager, closing
from base.smartpool import Connection
query_logger = None
__all__ = [
"transaction",
"lock_str",
"MySQLdbConnection",
]
#################
def total_seconds(td):
return td.days * 60 * 60 * 24 + td.seconds
def log(ident, msg, logger):
if logger is None:
return
logger("%d - %s" % (ident, msg))
def qlog(conn, msg):
cid = id(conn)
log(cid, msg, query_logger)
def active_time(old_handler):
def new_handler(self, *args, **kwargs):
self._last_active_time = datetime.now()
ret = old_handler(self, *args, **kwargs)
self._last_active_time = datetime.now()
return ret
return new_handler
def ready(old_handler):
def new_handler(self, *args, **kwargs):
if self._conn is None and self.reusable:
self.connect()
return old_handler(self, *args, **kwargs)
return new_handler
#######################
class Job(object):
"""
A indicator to mark whether the job is finished.
"""
def __init__(self):
self._finished = False
def is_finished(self):
return self._finished
def finish(self):
self._finished = True
@contextmanager
def transaction(conn):
"""
Automatic handle transaction COMMIT/ROLLBACK. You MUST call trans.finish(),
if you want to COMMIT; Otherwise(not call or exception occurs), ROLLBACK.
>>> with transaction(conn) as trans:
>>> do something...
>>> if xxxxx:
>>> # if you don't want to commit, you just not call trans.finish().
>>> return error_page("xxxxxx")
>>> # if you want to commit, you call:
>>> trans.finish()
@param conn: database connection
"""
trans = Job()
conn.begin()
try:
yield trans
except:
conn.rollback()
raise
if trans.is_finished():
conn.commit()
else:
conn.rollback()
@contextmanager
def lock_str(conn, s, timeout=0):
"""
Automatic handle lock/release a database string lock.
>>> with lock_str(conn, s, timeout) as locked:
>>> if not locked:
>>> # lock 's' failed
>>> do something
>>> # after the block, the lock will be automatic released
@param conn: database connection
@param s: the string wanted to lock
@param timeout: how many seconds to wait for getting the lock
"""
locked = False
try:
locked = conn.lock(s, timeout)
yield locked
finally:
if locked:
conn.release(s)
###########################################
class MySQLdbConnection(Connection):
def __init__(self, **db_config):
super(MySQLdbConnection, self).__init__(**db_config)
# private
self._conn = None
self._locks = []
self._in_trans = False
self._last_active_time = None
def __deepcopy__(self, memo):
return self
@property
def in_trans(self):
return self._in_trans
@property
def has_lock(self):
return len(self._locks) > 0
################ pool interface #################
@property
def reusable(self):
return not (self.in_trans or self.has_lock)
@property
def idle(self):
if self._last_active_time is None:
return 0
nowtime = datetime.now()
return total_seconds(nowtime - self._last_active_time)
def ping(self):
qlog(self, "ping")
if self._conn is None:
return False
try:
self._conn.ping()
return True
except MySQLdb.DatabaseError:
return False
@active_time
def connect(self):
qlog(self, "connect")
self._conn = MySQLdb.connect(**self._db_config)
self._conn.autocommit(True)
def close(self):
qlog(self, "close")
if self._conn is None:
return
try:
self._conn.close()
finally:
self._conn = None
def make_reusable(self):
if self.in_trans:
self.rollback()
if self.has_lock:
for key in self._locks:
self.release(key)
############## base dbop #############
@ready
@active_time
def select(self, sql, params=None, dict_cursor=False):
qlog(self, "execute: %s - %s" % (sql, repr(params)))
cursor = None
if dict_cursor:
cursor = self._conn.cursor(MySQLdb.cursors.DictCursor)
else:
cursor = self._conn.cursor()
with closing(cursor) as cur:
if params is None:
cur.execute(sql)
else:
cur.execute(sql, params)
return cur.fetchall()
@ready
@active_time
def insert(self, sql, params=None):
qlog(self, "execute: %s - %s" % (sql, repr(params)))
cursor = self._conn.cursor()
with closing(cursor) as cur:
if params is None:
cur.execute(sql)
else:
cur.execute(sql, params)
return cur.lastrowid
@ready
@active_time
def execute(self, sql, params=None):
qlog(self, "execute: %s - %s" % (sql, repr(params)))
cursor = self._conn.cursor()
with closing(cursor) as cur:
if params is None:
return cur.execute(sql)
else:
return cur.execute(sql, params)
############### unreusable #############
def begin(self):
if self._in_trans:
raise Exception("nested trans is not allowed")
self.execute("begin")
self._in_trans = True
def rollback(self):
self.execute("rollback")
self._in_trans = False
def commit(self):
self.execute("commit")
self._in_trans = False
def lock(self, key, timeout=0):
locked = self.select("SELECT GET_LOCK(%s, %s)", (key, timeout))[0][0] == 1
if locked:
self._locks.append(key)
return locked
def release(self, key):
released = self.select("SELECT RELEASE_LOCK(%s)", (key, ))[0][0] == 1
if released and key in self._locks:
self._locks.remove(key)
return released