-
Notifications
You must be signed in to change notification settings - Fork 9
/
dal.py
286 lines (267 loc) · 10.2 KB
/
dal.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
283
284
285
286
# -*- coding: utf-8 -*-
import os
import oursql
import werkzeug.contrib.cache
from common import (EXCLUDED, PAGINATION)
from log import tlog
DB_CONFIG_PATH = os.path.expanduser('~/replica.my.cnf')
HT_DB_HOST = 'tools.db.svc.eqiad.wmflabs'
HT_DB_NAME = 's52467__new_hashtags'
CACHE_EXPIRATION = 5 * 60
_cur_dir = os.path.dirname(__file__)
_cache_dir = os.path.join(_cur_dir, '../cache')
Cache = werkzeug.contrib.cache.FileSystemCache(_cache_dir)
class HashtagDatabaseConnection(object):
def __init__(self):
self.connect()
def connect(self, read_default_file=DB_CONFIG_PATH):
with tlog.critical('connect') as rec:
self.connection = oursql.connect(db=HT_DB_NAME,
host=HT_DB_HOST,
read_default_file=read_default_file,
charset=None,
use_unicode=False,
autoping=True)
def execute(self, query, params, cache_name=None, show_tables=False):
if cache_name:
results = Cache.get(cache_name)
if results:
return results
if not self.connection:
self.connect()
cursor = self.connection.cursor(oursql.DictCursor, show_table=show_tables)
try:
cursor.execute(query, params)
except Exception as e:
self.connect() # Reconnecting
cursor = self.connection.cursor(oursql.DictCursor, show_table=show_tables)
cursor.execute(query, params)
results = cursor.fetchall()
if cache_name:
Cache.set(cache_name, results, timeout=CACHE_EXPIRATION)
return results
def get_hashtags(self,
tag=None,
lang=None,
start=0,
end=PAGINATION,
startdate=None,
enddate=None):
if not tag:
return self.get_all_hashtags(lang=lang,
start=start,
end=end,
startdate=startdate,
enddate=enddate)
if tag and tag[0] == '#':
tag = tag[1:]
if not lang:
lang = '%'
query = '''
SELECT *
FROM recentchanges AS rc
JOIN hashtag_recentchanges AS htrc
ON htrc.htrc_id = rc.htrc_id
JOIN hashtags AS ht
ON ht.ht_id = htrc.ht_id
WHERE ht.ht_text = ?
AND rc.htrc_lang LIKE ?
AND rc.rc_timestamp BETWEEN ? AND ?
ORDER BY rc.rc_timestamp DESC
LIMIT ?, ?'''
params = (tag, lang, startdate, enddate, start, end)
with tlog.critical('get_hashtags') as rec:
ret = self.execute(query, params)
rec.success('Fetched revisions tagged with {tag}',
tag=tag)
return ret
def get_all_hashtags(self,
lang=None,
start=0,
end=PAGINATION,
startdate=None,
enddate=None):
"""Rules for hashtags:
1. Does not include MediaWiki magic words
(like #REDIRECT) or parser functions
2. Must be longer than one character
3. Must contain at least one non-numeric
character.
"""
if not lang:
lang = '%'
query = '''
SELECT *
FROM recentchanges AS rc
JOIN hashtag_recentchanges AS htrc
ON htrc.htrc_id = rc.htrc_id
JOIN hashtags AS ht
ON ht.ht_id = htrc.ht_id
WHERE rc.rc_type = 0
AND rc.htrc_lang LIKE ?
AND ht.ht_text NOT IN(%s)
AND ht.ht_text REGEXP '[[:alpha:]]+'
AND CHAR_LENGTH(ht.ht_text) > 1
AND rc.rc_timestamp BETWEEN ? AND ?
ORDER BY rc.rc_id DESC
LIMIT ?, ?''' % ', '.join(['?' for i in range(len(EXCLUDED))])
params = (lang,) + EXCLUDED + (startdate, enddate, start, end)
with tlog.critical('get_all_hashtags') as rec:
ret = self.execute(query, params)
rec.success('Fetched all hashtags starting at {start}',
start=start)
return ret
def get_top_hashtags(self, limit=10, recent_count=100000, nobots=True):
"""Gets the top hashtags from an arbitrarily "recent" group of edits
(not all time).
"""
excluded_p = ', '.join(['?' for i in range(len(EXCLUDED))])
if nobots:
bot_condition = 'AND rc_bot = 0'
else:
bot_condition = ''
query_tmpl = '''
SELECT ht.ht_text,
COUNT(ht.ht_text) AS count
FROM recentchanges AS rc
JOIN hashtag_recentchanges AS htrc
ON htrc.htrc_id = rc.htrc_id
AND rc.htrc_id > (SELECT MAX(htrc_id)
FROM recentchanges) - ?
JOIN hashtags AS ht
ON ht.ht_id = htrc.ht_id
WHERE ht.ht_text REGEXP '[[:alpha:]]{1}[[:alnum:]]+'
AND ht.ht_text NOT IN (%s)
%s
GROUP BY ht.ht_text
ORDER BY count DESC
LIMIT ?;'''
query = query_tmpl % (excluded_p, bot_condition)
params = (recent_count,) + EXCLUDED + (limit,)
# This query is cached because it's loaded for each visit to
# the index page
with tlog.critical('get_top_hashtags') as rec:
ret = self.execute(query, params, cache_name='top-tags-%s-%s' % (nobots, limit))
rec.success('Fetched top tags with limit of {limit}',
limit=limit)
return ret
def get_langs(self):
query = '''
SELECT htrc_lang
FROM recentchanges
GROUP BY htrc_lang'''
params = ()
with tlog.critical('get_langs') as rec:
ret = self.execute(query, params, cache_name='langs')
rec.success('Fetched available languages')
return ret
def get_hashtag_stats(self,
tag,
lang=None,
startdate=None,
enddate=None):
if not tag:
return self.get_all_hashtag_stats(lang=lang, startdate=startdate, enddate=enddate)
if tag and tag[0] == '#':
tag = tag[1:]
if not lang:
lang = '%'
query = '''
SELECT COUNT(*) as revisions,
COUNT(DISTINCT rc_user) as users,
COUNT(DISTINCT rc_title) as pages,
COUNT(DISTINCT htrc_lang) as langs,
MIN(rc_timestamp) as oldest,
MAX(rc_timestamp) as newest,
SUM(ABS(rc_new_len - rc_old_len)) as bytes
FROM recentchanges AS rc
JOIN hashtag_recentchanges AS htrc
ON htrc.htrc_id = rc.htrc_id
JOIN hashtags AS ht
ON ht.ht_id = htrc.ht_id
WHERE ht.ht_text = ?
AND rc.htrc_lang LIKE ?
AND rc.rc_timestamp BETWEEN ? AND ?
ORDER BY rc.rc_id DESC'''
params = (tag, lang, startdate, enddate)
with tlog.critical('get_hashtag_stats') as rec:
ret = self.execute(query, params)
rec.success('Fetched stats for {tag}',
tag=tag)
return ret
def get_all_hashtag_stats(self, lang=None, startdate=None, enddate=None):
# TODO: Add conditions here
if not lang:
lang = '%'
query = '''
SELECT COUNT(*) as revisions,
COUNT(DISTINCT rc_user) as users,
COUNT(DISTINCT rc_title) as pages,
MIN(rc_timestamp) as oldest,
MAX(rc_timestamp) as newest,
SUM(ABS(rc_new_len - rc_old_len)) as bytes
FROM recentchanges AS rc
JOIN hashtag_recentchanges AS htrc
ON htrc.htrc_id = rc.htrc_id
JOIN hashtags AS ht
ON ht.ht_id = htrc.ht_id
WHERE rc.rc_type = 0
AND rc.htrc_lang LIKE ?
AND rc.rc_timestamp BETWEEN ? AND ?
AND ht.ht_text NOT IN(%s)
AND ht.ht_text REGEXP '[[:alpha:]]+' ''' % ', '.join(['?' for i in range(len(EXCLUDED))])
with tlog.critical('get_all_hashtag_stats') as rec:
ret = self.execute(query, (lang, startdate, enddate,) + EXCLUDED)
rec.success('Fetched all hashtag stats')
return ret
def get_mentions(self, name=None, start=0, end=PAGINATION):
if not name:
return self.get_all_mentions(start, end)
if name and name[0] == '@':
tag = tag[1:]
query = '''
SELECT *
FROM recentchanges AS rc
JOIN mention_recentchanges AS mnrc
ON mnrc.mnrc_id = rc.htrc_id
JOIN mentions AS mn
ON mn.mn_id = mnrc.mn_id
WHERE mn.mn_text = ?
ORDER BY rc.rc_id DESC
LIMIT ?, ?'''
params = (name, start, end)
return self.execute(query, params)
def get_all_mentions(self, start=0, end=PAGINATION):
query = '''
SELECT *
FROM recentchanges AS rc
JOIN mention_recentchanges AS mnrc
ON mnrc.mnrc_id = rc.htrc_id
JOIN mentions AS mn
ON mn.mn_id = mnrc.mn_id
ORDER BY rc.rc_id DESC
LIMIT ?, ?'''
return self.execute(query, (start, end))
def get_run_log(self, limit=50000):
query = '''
SELECT *
FROM start_log AS sl
JOIN complete_log AS cl
ON sl.run_uuid = cl.run_uuid
WHERE cl.complete_timestamp > DATE_SUB(NOW(), INTERVAL 3 DAY)
ORDER BY cl.complete_timestamp DESC
LIMIT ?'''
with tlog.critical('get_run_log') as rec:
return self.execute(query, (limit,), show_tables=True)
def get_lang_run_log(self, lang, limit=50000, days=3):
query = '''
SELECT *
FROM start_log AS sl
JOIN complete_log AS cl
ON sl.run_uuid = cl.run_uuid
WHERE cl.lang = ?
AND cl.complete_timestamp > DATE_SUB(NOW(), INTERVAL ? DAY)
ORDER BY cl.complete_timestamp DESC
LIMIT ?'''
with tlog.critical('get_run_log') as rec:
return self.execute(query, (lang, days, limit), show_tables=True)