-
Notifications
You must be signed in to change notification settings - Fork 2
/
common_sql.py
executable file
·471 lines (413 loc) · 19.3 KB
/
common_sql.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
from flask import Flask, current_app, g
from collections import defaultdict as dd
from os import path
def qs(ll):
"""return len(l) ?s sepeated by ',' to use in queries"""
return ','.join('?' for l in ll)
app = Flask(__name__)
with app.app_context():
ROOT = path.dirname(path.realpath(__file__))
ADMINDB = 'db/admin.db'
CALLIGDB = 'db/callig.db'
LCCDB = 'db/lcc.db'
NTUCLEX = 'db/ntucleX.db'
###########################################################################
# SET UP CONNECTIONS
###########################################################################
def connect_admin():
return sqlite3.connect(path.join(ROOT, ADMINDB))
def connect_callig():
return sqlite3.connect(path.join(ROOT, CALLIGDB))
def connect_lcc():
return sqlite3.connect(path.join(ROOT, LCCDB))
def connect_ntucleX():
return sqlite3.connect(path.join(ROOT, NTUCLEX))
def query_admin(query, args=(), one=False):
cur = g.admin.execute(query, args)
rv = [dict((cur.description[idx][0], value)
for idx, value in enumerate(row)) for row in cur.fetchall()]
return (rv[0] if rv else None) if one else rv
def query_callig(query, args=(), one=False):
cur = g.callig.execute(query, args)
rv = [dict((cur.description[idx][0], value)
for idx, value in enumerate(row)) for row in cur.fetchall()]
return (rv[0] if rv else None) if one else rv
def query_lcc(query, args=(), one=False):
cur = g.lcc.execute(query, args)
rv = [dict((cur.description[idx][0], value)
for idx, value in enumerate(row)) for row in cur.fetchall()]
return (rv[0] if rv else None) if one else rv
def query_ntucleX(query, args=(), one=False):
cur = g.ntucleX.execute(query, args)
rv = [dict((cur.description[idx][0], value)
for idx, value in enumerate(row)) for row in cur.fetchall()]
return (rv[0] if rv else None) if one else rv
def write_admin(query, args=(), one=False):
cur = g.admin.cursor()
cur.execute(query, args)
lastid = cur.lastrowid
g.admin.commit()
return lastid
def write_callig(query, args=(), one=False):
cur = g.callig.cursor()
cur.execute(query, args)
lastid = cur.lastrowid
g.callig.commit()
return lastid
def write_lcc(query, args=(), one=False):
cur = g.lcc.cursor()
cur.execute(query, args)
lastid = cur.lastrowid
g.lcc.commit()
return lastid
def write_ntucleX(query, args=(), one=False):
cur = g.ntucleX.cursor()
cur.execute(query, args)
lastid = cur.lastrowid
g.ntucleX.commit()
return lastid
###########################################################################
# ADMIN SQL
###########################################################################
def fetch_userid(userID):
user = None
for r in query_admin("""SELECT userID, password,
access_level, access_group, full_name
FROM users
WHERE userID = ?""", [userID]):
if r['userID']:
user = (r['userID'], r['password'],
r['access_level'], r['access_group'], r['full_name'])
return user
def fetch_id_from_userid(userID):
for r in query_admin("""SELECT id
FROM users
WHERE userID = ?""", [userID]):
return r['id']
def fetch_allusers():
users = dd()
for r in query_admin("""SELECT * FROM users"""):
users[r['id']] = r
return users
###########################################################################
# CALLIG SQL
###########################################################################
###########################################################################
# CALLIG: SEX WITH ME
###########################################################################
def write_sexwithme(prompt, answer, seconds,
language, username, timestamp):
"""
Returns the ID of the recently added entry.
"""
return write_callig("""INSERT INTO sex_with_me (prompt, answer,
seconds, language,
username, timestamp)
VALUES (?,?,?,?,?,?)""",
[prompt, answer, seconds,
language, username, timestamp])
def write_sexwithme_feedback(answer, sex_with_me_id, feedback,
seconds, language, username, timestamp):
"""
Returns the ID of the recently added entry.
"""
return write_callig("""INSERT INTO sex_with_me_feedback
(answer, sex_with_me_id, feedback,
seconds, language, username, timestamp)
VALUES (?,?,?,?,?,?,?)""",
[answer, sex_with_me_id, feedback,
seconds, language, username, timestamp])
def fetch_sexwithme_30():
result = dd()
for r in query_callig("""SELECT * FROM sex_with_me WHERE answer IS NOT NULL
ORDER BY timestamp DESC LIMIT 30"""):
result[r['id']] = [r['prompt'], r['answer'],
r['seconds'], r['language'],
r['username'], r['timestamp']]
return result
###########################################################################
# CALLIG: WICKED PROVERBS
###########################################################################
def write_wickedproverbs(frame, w1, w2, proverb, explanation, seconds,
language, username, timestamp):
"""
Returns the ID of the recently added entry.
"""
return write_callig("""INSERT INTO wicked_proverbs
(frame, w1, w2, proverb, explanation, seconds,
language, username, timestamp)
VALUES (?,?,?,?,?,?,?,?,?)""",
[frame, w1, w2, proverb, explanation, seconds,
language, username, timestamp])
def fetch_wickedproverbs_30(limit=30):
if (type(limit) != int):
limit = 30
result = dd()
for r in query_callig("""SELECT * FROM wicked_proverbs
WHERE proverb IS NOT NULL
AND explanation IS NOT NULL
ORDER BY timestamp DESC LIMIT 30"""):
result[r['id']] = [r['frame'], r['proverb'], r['explanation'],
r['seconds'], r['language'],
r['username'], r['timestamp']]
return result
###########################################################################
# CALLIG: FORCED LINKS
###########################################################################
def write_forcedlinks(w1, w2, links_json, timestamps_json,
seconds, language, username, timestamp):
"""
Returns the ID of the recently added entry.
"""
return write_callig("""INSERT INTO forced_links
(w1, w2, links_json, timestamps_json,
seconds, language, username, timestamp)
VALUES (?,?,?,?,?,?,?,?)""",
[w1, w2, links_json, timestamps_json,
seconds, language, username, timestamp])
def fetch_forcedlinks(limit=30):
if (type(limit) != int):
limit = 30
result = dd()
for r in query_callig("""SELECT * FROM forced_links
WHERE links_json IS NOT NULL
AND links_json IS NOT NULL
ORDER BY timestamp DESC LIMIT ?
""", [limit]):
result[r['id']] = [r['w1'], r['w2'], r['links_json'],
r['timestamps_json'], r['seconds'],
r['language'], r['username'], r['timestamp']]
return result
###########################################################################
# CALLIG: HAIKU ON DEMAND
###########################################################################
def write_haikuondemand(title, l1, l2, l3,
seconds, language, username, timestamp):
"""
Returns the ID of the recently added entry.
"""
return write_callig("""
INSERT INTO haiku_on_demand
(title, l1, l2, l3,
seconds, language, username, timestamp)
VALUES (?,?,?,?,?,?,?,?)
""", [title, l1, l2, l3,
seconds, language, username, timestamp])
def write_haikuondemand_feedback(title, feedback, l1, l2, l3, s1, s2, s3,
seconds, language, username, timestamp):
"""
Returns the ID of the recently added entry.
"""
return write_callig("""
INSERT INTO haiku_on_demand_feedback
(title, feedback, l1, l2, l3, s1, s2, s3,
seconds, language, username, timestamp)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
""", [title, feedback, l1, l2, l3, s1, s2, s3,
seconds, language, username, timestamp])
def fetch_haikuondemand_30():
result = dd()
for r in query_callig("""
SELECT * FROM haiku_on_demand
WHERE l1 IS NOT NULL
AND l2 IS NOT NULL
AND l3 IS NOT NULL
ORDER BY timestamp DESC LIMIT 30
"""):
result[r['id']] = [r['title'], r['l1'], r['l2'], r['l3'],
r['username'], r['timestamp'], r['seconds']]
return result
###########################################################################
# LCC SQL
###########################################################################
# With the addition of new databases, these SQL functions now need to take
# an extra argument pointing to the db to be used. The default database
# should be lcc.db, and if added, ntucleX.db should point to the permanent
# corpus database.
###########################################################################
def fetch_max_doc_id(db="lcc.db"):
if db == "ntucleX.db":
for r in query_ntucleX("""SELECT MAX(docid) from doc"""):
if r['MAX(docid)']:
return r['MAX(docid)']
else:
return 0
else:
for r in query_lcc("""SELECT MAX(docid) from doc"""):
if r['MAX(docid)']:
return r['MAX(docid)']
else:
return 0
def fetch_max_sid(db="lcc.db"):
if db == "ntucleX.db":
for r in query_ntucleX("""SELECT MAX(sid) from sent"""):
if r['MAX(sid)']:
return r['MAX(sid)']
else:
return 0
else:
for r in query_lcc("""SELECT MAX(sid) from sent"""):
if r['MAX(sid)']:
return r['MAX(sid)']
else:
return 0
def fetch_sents_by_docid(docid, db="lcc.db"):
sents = dd()
if db == "ntucleX.db":
for r in query_ntucleX("""SELECT sid, sent from sent
WHERE docid = ?
""", [docid]):
sents[r['sid']] = r['sent']
else:
for r in query_lcc("""SELECT sid, sent from sent
WHERE docid = ?
""", [docid]):
sents[r['sid']] = r['sent']
return sents
def fetch_sent_words_by_sid(sid, db="lcc.db"):
sent = ""
words = dd()
if db == "ntucleX.db":
for r in query_ntucleX("""SELECT sent, wid, word, pos, lemma
FROM sent JOIN word
WHERE sent.sid = word.sid
AND sent.sid = ?
""", [sid]):
words[r['wid']] = [r['word'], r['pos'], r['lemma']]
sent = r['sent']
else:
for r in query_lcc("""SELECT sent, wid, word, pos, lemma
FROM sent JOIN word WHERE sent.sid = word.sid
AND sent.sid = ?
""", [sid]):
words[r['wid']] = [r['word'], r['pos'], r['lemma']]
sent = r['sent']
return sent, words
def fetch_dochtml_by_docid(docid, db="lcc.db"):
dochtml = dd()
if db == "ntucleX.db":
for r in query_ntucleX("""SELECT docid, doc FROM doc
WHERE docid = ?
""", [docid]):
dochtml = r['doc']
else:
for r in query_lcc("""SELECT docid, doc FROM doc
WHERE docid = ?
""", [docid]):
dochtml = r['doc']
return dochtml
def fetch_all_doc_titles(db="lcc.db"):
docs = dd()
if db == "ntucleX.db":
for r in query_ntucleX("""SELECT docid, title FROM doc
WHERE title != 'single_sentence' """):
docs[r['docid']] = r['title']
else:
for r in query_lcc("""SELECT docid, title FROM doc
WHERE title != 'single_sentence' """):
docs[r['docid']] = r['title']
return docs
def fetch_words_by_sid(sid_min, sid_max, db="lcc.db"):
words = dd(lambda: dd())
if db == "ntucleX.db":
for r in query_ntucleX("""SELECT sid, wid, word, pos, lemma from word
WHERE sid >= ? AND sid <= ?
""", [sid_min, sid_max]):
words[r['sid']][r['wid']] = [r['word'], r['pos'], r['lemma']]
else:
for r in query_lcc("""SELECT sid, wid, word, pos, lemma from word
WHERE sid >= ? AND sid <= ?
""", [sid_min, sid_max]):
words[r['sid']][r['wid']] = [r['word'], r['pos'], r['lemma']]
return words
def fetch_max_wid(sid, db="lcc.db"):
if db == "ntucleX.db":
for r in query_ntucleX("""SELECT MAX(wid) FROM word
WHERE sid = ?""",
[sid]):
if r['MAX(wid)']:
return r['MAX(wid)']
else:
return 0
else:
for r in query_lcc("""SELECT MAX(wid) from word WHERE sid = ?""",
[sid]):
if r['MAX(wid)']:
return r['MAX(wid)']
else:
return 0
def fetch_all_sents(db="lcc.db"):
sents = dd()
if db == "ntucleX.db":
for r in query_ntucleX("""SELECT sid, docID, sent from sent"""):
sents[r['sid']] = [r['sent'], r['docID']]
else:
for r in query_lcc("""SELECT sid, docID, sent from sent"""):
sents[r['sid']] = [r['sent'], r['docID']]
return sents
def fetch_all_errors(db="lcc.db"):
errors_by_sent = dd(lambda: list())
errors_by_label = dd(lambda: list())
if db == "ntucleX.db":
for r in query_ntucleX("""SELECT sid, eid, label, comment from error
"""):
errors_by_sent[r['sid']].append((r['eid'], r['label'],
r['comment']))
errors_by_label[r['label']].append((r['sid'], r['eid'],
r['comment']))
else:
for r in query_lcc("""SELECT sid, eid, label, comment from error
"""):
errors_by_sent[r['sid']].append((r['eid'], r['label'],
r['comment']))
errors_by_label[r['label']].append((r['sid'], r['eid'],
r['comment']))
return errors_by_sent, errors_by_label
def insert_into_doc(docid, docname, db="lcc.db"):
if db == "ntucleX.db":
return write_ntucleX("""INSERT INTO doc (docid, title)
VALUES (?,?)
""", [docid, docname])
else:
return write_lcc("""INSERT INTO doc (docid, title)
VALUES (?,?)
""", [docid, docname])
def update_html_into_doc(docid, html, db="lcc.db"):
if db == "ntucleX.db":
return write_ntucleX("""UPDATE doc SET doc = ?
WHERE docid = ?
""", [html, docid])
else:
return write_lcc("""UPDATE doc SET doc = ?
WHERE docid = ?
""", [html, docid])
def insert_into_sent(sid, docid, pid, sent, db="lcc.db"):
if db == "ntucleX.db":
return write_ntucleX("""INSERT INTO sent (sid, docID, pid, sent)
VALUES (?,?,?,?)
""", [sid, docid, pid, sent])
else:
return write_lcc("""INSERT INTO sent (sid, docID, pid, sent)
VALUES (?,?,?,?)
""", [sid, docid, pid, sent])
def insert_into_word(sid, wid, word, pos, lemma, db="lcc.db"):
if db == "ntucleX.db":
return write_ntucleX("""INSERT INTO word (sid, wid, word, pos, lemma)
VALUES (?,?,?,?,?)
""", [sid, wid, word, pos, lemma])
else:
return write_lcc("""INSERT INTO word (sid, wid, word, pos, lemma)
VALUES (?,?,?,?,?)
""", [sid, wid, word, pos, lemma])
def insert_into_error(sid, eid, label, comment, db="lcc.db"):
if db == "ntucleX.db":
return write_ntucleX("""INSERT INTO error (sid, eid, label, comment)
VALUES (?,?,?,?)
""", [sid, eid, label, comment])
else:
return write_lcc("""INSERT INTO error (sid, eid, label, comment)
VALUES (?,?,?,?)
""", [sid, eid, label, comment])