-
Notifications
You must be signed in to change notification settings - Fork 11
/
query.py
1845 lines (1620 loc) · 66.5 KB
/
query.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf8
# Library to query the database and update scoring information. Raw data entry
# from logfile and milestones is done in loaddb.py, this is for queries and
# post-processing.
import logging
from logging import debug, info, warn, error
import loaddb
from loaddb import query_do, query_first, query_row, query_rows, BOT_USERS
from loaddb import query_rows_with_ties
from loaddb import query_first_col, query_first_def
from query_class import Query
import scoring_data
from scoring_data import INDIVIDUAL_CATEGORIES, MAX_CATEGORY_SCORE, CLAN_CATEGORIES
import combos
import crawl
import crawl_utils
import uniq
import os.path
import re
from datetime import datetime
import time
import json
MAX_RUNES = 15
MAX_GEMS = 11
LOG_FIELDS = [ 'source_file' ] + [ x[1] for x in loaddb.LOG_DB_MAPPINGS ]
def _cursor():
"""Easy retrieve of cursor to make interactive testing easier."""
d = loaddb.connect_db()
return d.cursor()
def _filter_invalid_where(d):
if loaddb.is_not_tourney(d):
return None
status = d['status']
if status in [ 'quit', 'won', 'bailed out', 'dead' ]:
return None
else:
d['status'] = status.title() or 'Active'
return d
def time_from_str(when):
if isinstance(when, datetime):
return when
if when.endswith('D') or when.endswith('S'):
when = when[:-1]
return datetime(*(time.strptime(when, '%Y%m%d%H%M%S')[0:6]))
def game_is_over(c, name, start):
query = Query('''SELECT COUNT(*) FROM games WHERE player=%s
AND start_time=%s''', name, start)
return (query.count(c) > 0)
def whereis_player(c, name, src):
mile = query_row(c, '''SELECT start_time, mile_time
FROM whereis_table
WHERE player = %s AND src = %s''', name, src)
if not mile:
return None
last_game = query_row(c, '''SELECT start_time
FROM last_game_table
WHERE player = %s AND src = %s''', name, src)
if last_game and last_game[0] >= mile[0]:
return None
return query_row(c, '''SELECT milestone_time, player, title, xl, charabbrev,
god, milestone, place, turn, duration
FROM milestones
WHERE player = %s
AND start_time = %s
AND milestone_time = %s''',
name, mile[0], mile[1])
def whereis_all_players(c):
whereis_list = []
rows = query_rows(c, '''SELECT player, src, start_time, mile_time
FROM whereis_table''')
for r in rows:
last_game = query_row(c, '''SELECT start_time
FROM last_game_table
WHERE player = %s AND src = %s''', r[0], r[1])
if last_game and last_game[0] >= r[2]:
continue
mile = query_row(c, '''SELECT milestone_time, player, title, xl, charabbrev,
god, place, runes
FROM milestones
WHERE player = %s
AND start_time = %s
AND milestone_time = %s''',
r[0], r[2], r[3])
whereis_list.append((r[1], mile))
return whereis_list
def get_game_god(c, game):
game_god = game.get('god') or 'No God'
if (game_god == 'Xom' or game_god == 'Gozag' or game_god == 'No God' \
or game_god =='Ignis') \
and not did_renounce_god(c, game['name'], game['start'], game['end']):
return game_god
return get_first_max_piety(c, game['name'], game['start'])
def count_god_wins(c, god, start_time=None):
q = Query('''SELECT COUNT(*) FROM player_won_gods
WHERE god=%s''', god)
if start_time:
q.append(' AND win_time < %s', start_time)
return q.first(c)
def is_unbeliever(c, game):
if game.get('god'):
return False
if game['raceabbr'] == 'Dg':
return False
if did_change_god(c, game):
return False
return True
def did_change_god(c, game):
"""Returns true if the player changed gods during the game, by checking
for a god.renounce or god.worship milestone."""
return (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND (verb = 'god.renounce'
OR verb = 'god.worship') ''',
game['name'], game['start']) > 0)
def did_renounce_god(c, name, start, end):
"""Returns true if the player renounced a god before end, by checking
for a god.renounce milestone."""
return (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'god.renounce'
AND milestone_time < %s ''',
name, start, end) > 0)
def did_worship_god(c, god, name, start, end):
return (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND (verb = 'god.renounce'
OR verb = 'god.worship')
AND noun = %s
AND milestone_time < %s ''',
name, start, god, end) > 0)
def did_use_ecumenical_altar(c, name, start, end):
"""Returns true if the player joined a new religion at an ecumenical
altar."""
return (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'god.ecumenical'
AND milestone_time < %s ''',
name, start, end) > 0)
def did_get_rune(c, rune, name, start, end):
return (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'rune'
AND noun = %s
AND milestone_time < %s ''',
name, start, rune, end) > 0)
def did_found_gem(c, gem, name, start, end):
return (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'gem.found'
AND noun = %s
AND milestone_time < %s ''',
name, start, gem, end) > 0)
def did_exit_branch(c, br, name, start, end):
return (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'br.exit'
AND noun = %s
AND milestone_time < %s ''',
name, start, br, end) > 0)
def did_enter_branch(c, br, name, start, end):
return (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'br.enter'
AND noun = %s
AND milestone_time < %s ''',
name, start, br, end) > 0)
def branch_end_turn(c, br, name, start):
return query_first(c, '''SELECT turn FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'br.end'
AND noun = %s ''', name, start, br)
def did_sacrifice(c, noun, name, start, end):
return (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'sacrifice'
AND noun = %s
AND milestone_time < %s ''',
name, start, noun, end) > 0)
def did_champion(c, god, name, start, end):
return (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'god.maxpiety'
AND noun = %s
AND milestone_time < %s ''',
name, start, god, end) > 0)
def win_query(selected, order_by = None,
player=None, charabbr=None, character_race=None, raceabbr=None,
character_class=None, classabbr=None, runes=None, found_gems=None, intact_gems=None,
before=None, after=None, limit=None):
table = 'games'
query = Query("SELECT " + selected + " FROM " + table +
" WHERE killertype='winning' ")
if player:
query.append(' AND player=%s', player)
if (charabbr):
query.append(' AND charabbrev=%s', charabbr)
if (character_race):
query.append(' AND race=%s', character_race)
if (raceabbr):
query.append(' AND MID(charabbrev,1,2) = %s', raceabbr)
if (character_class):
query.append(' AND class=%s', character_class)
if (classabbr):
query.append(' AND MID(charabbrev,3,2) = %s', classabbr)
if (runes):
query.append(' AND runes >= %s', runes)
if (found_gems):
query.append(' AND found_gems >= %s', found_gems)
if (intact_gems):
query.append(' AND intact_gems >= %s', intact_gems)
if before:
query.append(' AND end_time < %s', before)
if after:
query.append(' AND start_time > %s', after)
if order_by:
query.append(' ' + order_by)
if limit:
query.append(" LIMIT %d" % limit)
return query
def first_win_for_combo(c, charabbrev, game_end):
table = 'games'
return query_first(c, "SELECT COUNT(*) FROM " + table +
""" WHERE killertype = 'winning' AND charabbrev = %s
AND end_time < %s""",
charabbrev, game_end) == 0
def get_player_won_gods(c, player):
"""Returns the names of all the gods that the player has won games with,
wins counting only if the player has not switched gods during the game."""
return query_first_col(c,
"SELECT DISTINCT god FROM player_won_gods WHERE player = %s",
player)
def get_player_best_streak_games(c, player):
streaks = list_all_streaks(c, player)
if len(streaks) > 0:
return streaks[0][3]
return None
def player_top_scores(c, limit=5):
return query_rows(c, '''SELECT player, score
FROM games
ORDER BY score DESC
LIMIT %d''' % limit)
def logfile_fields(prefix = None):
if prefix:
return ",".join([ prefix + x for x in LOG_FIELDS ])
else:
return ",".join(LOG_FIELDS)
def get_top_active_streaks(c, limit = None):
streaks = list_all_streaks(c, None, True)
if limit and len(streaks) > limit:
streaks = streaks[:hlimit]
return streaks
def get_top_streaks(c, limit = None):
streaks = list_all_streaks(c)
filtered_streaks = []
for streak in streaks:
if streak[0] in [s[0] for s in filtered_streaks]:
continue
filtered_streaks.append(streak)
if limit and len(filtered_streaks) > limit:
filtered_streaks = filtered_streaks[:limit]
return filtered_streaks
def get_combo_scores(c, how_many=None, player=None):
query = Query("SELECT " + ",".join(LOG_FIELDS) +
(""" FROM combo_highscores
%s
ORDER BY score DESC, charabbrev""" %
(player and 'WHERE player = %s' or '')))
if player is not None:
query.vappend(player)
if how_many:
query.append(" LIMIT %d" % how_many)
return [ row_to_xdict(x) for x in query.rows(c) ]
def highscore(c, combo):
return query_first_def(c, 0, '''SELECT score FROM games
WHERE charabbrev = %s
ORDER BY score DESC''',
combo)
def previous_combo_highscore(c, game):
return query_row(c, '''SELECT player, score, killertype
FROM games
WHERE charabbrev = %s
AND end_time < %s
ORDER BY score DESC''',
game['char'], game['end'])
def previous_species_highscore(c, game):
return query_row(c, '''SELECT player, score, killertype
FROM games
WHERE raceabbr = %s
AND end_time < %s
ORDER BY score DESC''',
game['char'][:2], game['end'])
def previous_class_highscore(c, game):
return query_row(c, '''SELECT player, score, killertype
FROM games
WHERE MID(charabbrev,3,2) = %s
AND end_time < %s
ORDER BY score DESC''',
game['char'][2:], game['end'])
def get_species_scores(c, how_many=None, player=None):
query = Query("SELECT " + ",".join(LOG_FIELDS) +
(""" FROM species_highscores
%s
ORDER BY score DESC, race""" %
(player and 'WHERE player = %s' or '')))
if player is not None:
query.vappend(player)
if how_many:
query.append(" LIMIT %d" % how_many)
return [ row_to_xdict(x) for x in query.rows(c) ]
def get_class_scores(c, how_many=None, player=None):
query = Query("SELECT " + ",".join(LOG_FIELDS) +
(""" FROM class_highscores
%s
ORDER BY score DESC, class""" %
(player and 'WHERE player = %s' or '')))
if player is not None:
query.vappend(player)
if how_many:
query.append(" LIMIT %d" % how_many)
return [ row_to_xdict(x) for x in query.rows(c) ]
def get_death_causes(c):
rows = query_rows(c,
"""SELECT g.kgroup, g.killertype, COUNT(*) killcount,
(SELECT player FROM games
WHERE kgroup = g.kgroup
ORDER BY end_time DESC
LIMIT 1) latest
FROM games g
WHERE g.killertype NOT IN ('winning',
'quitting',
'leaving')
GROUP BY g.kgroup, g.killertype""")
# Now to fix up the rows.
clean_rows = [ ]
last = None
total = 0
for r in rows:
killer = r[0]
total += r[2]
if last and last[0] == killer:
if r[1] == 'mon':
kills_breakdown[0] += r[2]
else:
kills_breakdown[1] += r[2]
clean_rows.pop()
if kills_breakdown[0] > 0 and kills_breakdown[1] > 0:
killer = "%s (%d melee, %d ranged)" % (killer, kills_breakdown[0], kills_breakdown[1])
clean_rows.append( [ killer, kills_breakdown[0]+kills_breakdown[1], r[3] ] )
else:
if r[1] == 'mon':
kills_breakdown = [ r[2], 0 ]
else:
kills_breakdown = [ 0, r[2] ]
clean_rows.append( [ killer, r[2], r[3] ] )
last = r
clean_rows.sort(key=lambda a: int(a[1]))
r_art = re.compile(r'^an? ')
for r in clean_rows:
r[0] = r_art.sub('', r[0])
r[2] = crawl_utils.linked_text(r[2], crawl_utils.player_link)
r.insert(1, "%.2f%%" % calc_perc(r[1], total))
return clean_rows
def _canonicalize_player_name(c, player):
row = query_row(c, '''SELECT name FROM players WHERE name = %s''',
player)
if row:
return row[0]
return None
canonicalize_player_name = \
crawl_utils.Memoizer(_canonicalize_player_name, lambda args: args[1:])
def get_top_players(c, how_many=10):
return query_rows_with_ties(c,
'''SELECT name, score_full FROM players
WHERE score_full > 0''',
'score_full', how_many, 1)
def check_xl9_streak(c, player, start):
mile = query_row(c, '''SELECT start_time
FROM milestones
WHERE player = %s
AND verb = 'begin'
AND milestone_time < %s
ORDER BY milestone_time DESC''', player, start)
if not mile:
return False
game = query_row(c, '''SELECT end_time
FROM games
WHERE player = %s
AND xl > 8
AND end_time < %s
AND end_time > %s''', player, start, mile[0])
if game:
return True
return False
def count_wins(c, **selectors):
"""Return the number wins recorded for the given player, optionally with a
specific race, class, minimum number of runes, found gems, intact gems, or
any combination"""
return win_query('COUNT(start_time)', **selectors).count(c)
def get_wins(c, **selectors):
"""Returns the charabbrevs for wins matching the provided criteria,
ordered with earlier wins first."""
return [ x[0] for x in
win_query('charabbrev', order_by = 'ORDER BY end_time',
**selectors).rows(c) ]
def won_unwon_combos_with_games(cu, won_games):
won_combos = set([x['charabbrev'] for x in won_games])
combo_lookup = dict([(x['charabbrev'], x) for x in won_games])
def game_charabbrev_link(count, g):
if count > 1:
return crawl_utils.linked_text(g, crawl_utils.morgue_link,
"%s(%d)" % (g['charabbrev'], count))
return crawl_utils.linked_text(g, crawl_utils.morgue_link,
g['charabbrev'])
won_combo_list = [game_charabbrev_link(count_wins(cu, charabbr=c), combo_lookup[c])
for c in combos.VALID_COMBOS
if c in won_combos]
unwon_combo_list = [c for c in combos.VALID_COMBOS if c not in won_combos]
return (won_combo_list, unwon_combo_list)
def won_unwon_combos(c):
won_games = get_winning_games(c)
return won_unwon_combos_with_games(c, won_games)
def get_winning_games(c, **selectors):
"""Returns the games for wins matching the provided criteria, ordered
with earlier wins first. Exactly the same as get_wins, but returns
the xlog dictionaries instead of the charabbrev"""
if not 'limit' in selectors:
selectors['limit'] = None
return find_games(c, sort_max='end_time',
killertype='winning', **selectors)
def player_race_wins(c, name):
return query_rows(c, """SELECT DISTINCT MID(charabbrev,1,2) FROM
games WHERE killertype='winning' AND player=%s""", name)
def player_class_wins(c, name):
return query_rows(c, """SELECT DISTINCT MID(charabbrev,3,2) FROM
games WHERE killertype='winning' AND player=%s""", name)
def row_to_xdict(row):
return dict( zip(LOG_FIELDS, row) )
def find_clan_games(c, captain, sort_min=None, sort_max=None, limit=1,
**dictionary):
if sort_min is None and sort_max is None:
sort_min = 'end_time'
query = Query('SELECT ' + ",".join(LOG_FIELDS) + ' FROM games g, players p ' +
'''WHERE g.player = p.name
AND p.team_captain = %s''',
captain)
for key, value in dictionary.items():
query.append(' AND ' + key + ' = %s', value)
if sort_min:
query.append(' ORDER BY ' + sort_min)
elif sort_max:
query.append(' ORDER BY ' + sort_max + ' DESC')
if limit:
query.append(' LIMIT %d' % limit)
return [ row_to_xdict(x) for x in query.rows(c) ]
def find_games(c, sort_min=None, sort_max=None, limit=1, **dictionary):
"""Finds all games matching the supplied criteria, all criteria ANDed
together."""
if sort_min is None and sort_max is None:
sort_min = 'end_time'
table = 'games'
query = Query('SELECT ' + ",".join(LOG_FIELDS) + ' FROM ' + table)
where = []
values = []
def append_where(where, clause, *newvalues):
where.append(clause)
for v in newvalues:
values.append(v)
for key, value in dictionary.items():
if key == 'before':
append_where(where, "end_time < %s", value)
elif isinstance(value, (list, tuple)):
if len(value) == 2 and value[0] == 'not':
# TODO: make this less ad hoc somehow
append_where(where, key + " != %s", value[1])
else:
append_where(where, key + " IN (" +
",".join(['%s'] * len(value)) + ")", *value)
else:
append_where(where, key + " = %s", value)
order_by = ''
if sort_min:
order_by += ' ORDER BY ' + sort_min
elif sort_max:
order_by += ' ORDER BY ' + sort_max + ' DESC'
if where:
query.append(' WHERE ' + ' AND '.join(where), *values)
if order_by:
query.append(order_by)
if limit:
query.append(' LIMIT %d' % limit)
return [ row_to_xdict(x) for x in query.rows(c) ]
def num_uniques_killed(c, player):
"""Return the number of uniques the player has ever killed"""
query = Query('''SELECT COUNT(DISTINCT monster) FROM kills_of_uniques
WHERE player=%s;''',
player)
return query.count(c)
def was_unique_killed(c, player, monster):
"""Return whether the player killed the given unique"""
query = Query('''SELECT monster FROM kills_of_uniques
WHERE player=%s AND monster=%s LIMIT 1;''',
player, monster)
return query.row(c) is not None
def calc_perc(num, den):
if den <= 0:
return 0.0
else:
return num * 100.0 / den
def get_all_game_stats(c):
played = query_first(c, '''SELECT COUNT(*) FROM games
WHERE killertype NOT IN ('quitting', 'leaving', 'wizmode')''' +
' AND player NOT IN (' +
",".join(['%s'] * len(BOT_USERS)) + ")", *BOT_USERS)
distinct_players = query_first(c, '''SELECT COUNT(DISTINCT player) FROM games
WHERE killertype NOT IN ('quitting', 'leaving', 'wizmode')''' +
' AND player NOT IN (' +
",".join(['%s'] * len(BOT_USERS)) + ")", *BOT_USERS)
won = query_first(c, """SELECT COUNT(*) FROM games
WHERE killertype='winning'""" +
' AND player NOT IN (' +
",".join(['%s'] * len(BOT_USERS)) + ")", *BOT_USERS)
distinct_winners = query_first(c, """SELECT COUNT(DISTINCT player) FROM games
WHERE killertype='winning'""" +
' AND player NOT IN (' +
",".join(['%s'] * len(BOT_USERS)) + ")", *BOT_USERS)
allrune_won = query_first(c, """SELECT COUNT(*) FROM games
WHERE killertype='winning' AND nrune=15""" +
' AND player NOT IN (' +
",".join(['%s'] * len(BOT_USERS)) + ")", *BOT_USERS)
allrune_distinct_winners = query_first(c,
"""SELECT COUNT(DISTINCT player) FROM games
WHERE killertype='winning' and nrune=15""" +
' AND player NOT IN (' +
",".join(['%s'] * len(BOT_USERS)) + ")", *BOT_USERS)
win_perc = "%.2f%%" % calc_perc(won, played)
allrune_win_perc = "%.2f%%" % calc_perc(allrune_won, played)
played_text = "%d (%d players)" % (played, distinct_players)
won_text = "%d (%d players)" % (won, distinct_winners)
allrune_won_text = "%d (%d players)" % (allrune_won, allrune_distinct_winners)
return { 'played' : played_text,
'won' : won_text,
'allrune_won': allrune_won_text,
'win_perc' : win_perc,
'allrune_win_perc': allrune_win_perc }
def get_all_player_stats(c):
q = Query('''SELECT p.name, p.team_captain, t.name, p.score_full,
(SELECT COUNT(*) FROM games
WHERE player = p.name
AND killertype = 'winning') wincount,
(SELECT COUNT(*) FROM games
WHERE player = p.name) playcount
FROM players p LEFT JOIN teams t
ON p.team_captain = t.owner
ORDER BY p.score_full DESC, p.name''')
rows = [ list(r) for r in q.rows(c) ]
clean_rows = [ ]
for r in rows:
captain = r[1]
r = r[0:1] + r[2:]
if captain is None:
r[1] = ''
else:
r[1] = crawl_utils.linked_text(captain, crawl_utils.clan_link, r[1])
r.append( "%.2f%%" % calc_perc( r[3], r[4] + 1 ) )
clean_rows.append(r)
return clean_rows
def get_clan_stats(c, captain):
stats = { }
points = query_row(c, '''SELECT total_score FROM teams
WHERE owner = %s''',
captain)
if points is not None:
stats['points'] = points[0]
stats['rank1'] = query_first(c, '''SELECT COUNT(DISTINCT total_score) FROM teams
WHERE total_score > %s''',
stats['points']) + 1
stats['rank2'] = query_first(c, '''SELECT COUNT(DISTINCT total_score) FROM teams''')
stats['won'] = query_first(c, '''SELECT COUNT(*) FROM games g, players p
WHERE p.name = g.player
AND killertype = 'winning'
AND p.team_captain = %s''',
captain)
stats['played'] = query_first(c, '''SELECT COUNT(*) FROM games g, players p
WHERE p.name = g.player
AND p.team_captain = %s''',
captain)
stats['win_perc' ] = "%.2f%%" % calc_perc(stats['won'], stats['played'])
return stats
def get_player_stats(c, name):
"""Returns a dictionary of miscellaneous stats for the player."""
score_full = query_row(c, '''SELECT score_full
FROM players WHERE name = %s''',
name)
if score_full is None:
return { }
stats = { }
stats['score_full'] = score_full[0]
stats['rank1'] = query_first(c, '''SELECT COUNT(DISTINCT score_full) FROM players
WHERE score_full > %s''',
stats['score_full']) + 1
stats['rank2'] = query_first(c, '''SELECT COUNT(DISTINCT score_full) FROM players''')
# Get win/played stats.
stats['won'] = \
query_first(c,
"""SELECT COUNT(*) FROM games
WHERE player = %s AND killertype = 'winning'""",
name)
stats['played'] = \
query_first(c,
"""SELECT COUNT(*) FROM games WHERE player = %s""",
name)
stats['win_perc'] = "%.2f%%" % calc_perc(stats['won'], stats['played'] + 1)
return stats
def get_player_ranks(c, name):
"""Returns a dictionary of player ranks in different categories"""
ranks = query_row(c, '''SELECT '''
+ ",".join([ ic.rank_column for ic in
INDIVIDUAL_CATEGORIES ])
+ ''' FROM players WHERE name = %s''', name)
if ranks is None:
return None
return dict(zip( [ ic.name for ic in INDIVIDUAL_CATEGORIES ], ranks))
def get_players(c):
return [r[0] for r in
query_rows(c, 'SELECT name FROM players')]
def get_clans(c):
return [r[0] for r in query_rows(c, 'SELECT owner FROM teams')]
def is_god_repeated(c, player, god):
"""Returns true if the player has been credited as the champion of the
specified god."""
return query_first_def(c, False,
'''SELECT COUNT(*) FROM player_max_piety
WHERE player = %s AND COALESCE(god, '') = %s''',
player, god)
def is_god_win_repeated(c, player, god):
"""Returns true if the player has been credited as the winner of the
specified god."""
return query_first_def(c, False,
'''SELECT COUNT(*) FROM player_won_gods
WHERE player = %s AND COALESCE(god, '') = %s''',
player, god)
def record_won_god(c, player, god):
if is_god_win_repeated(c, player, god):
return False
query_do(c, "INSERT INTO player_won_gods VALUES (%s, %s)", player, god)
return True
def record_max_piety(c, player, start_time, god):
if is_god_repeated(c, player, god):
return False
if get_first_max_piety(c, player, start_time) == god:
query_do(c, "INSERT INTO player_max_piety VALUES (%s, %s)", player, god)
return True
return False
def get_first_max_piety(c, player, start_time):
row = query_row(c,
'''SELECT noun, milestone_time FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'god.maxpiety'
ORDER BY milestone_time ASC''',
player, start_time)
if row is None:
return 'faithless'
if (query_first(c,
'''SELECT COUNT(*) FROM milestones
WHERE player = %s AND start_time = %s
AND verb = 'god.renounce'
AND noun <> %s
AND milestone_time < %s''',
player, start_time, row[0], row[1]) > 0):
return 'faithless'
return row[0]
def count_player_unique_kills(cursor, player, unique):
return query_first(cursor,
'''SELECT COUNT(*) FROM kills_of_uniques
WHERE player=%s AND monster=%s''',
player, unique)
def player_count_distinct_runes(c, player):
return query_first(c, '''SELECT COUNT(DISTINCT rune)
FROM rune_finds
WHERE player = %s''',
player)
def player_count_distinct_found_gems(c, player):
return query_first(c, '''SELECT COUNT(DISTINCT gem)
FROM gem_finds
WHERE player = %s''',
player)
def player_count_invo_titles(c, player):
return query_first(c, '''SELECT COUNT(DISTINCT title)
FROM games
WHERE player = %s
AND killertype = 'winning'
AND skill = 'Invocations' ''',
player)
def player_count_runes(cursor, player, rune=None):
"""Counts the number of times the player has found runes (or a specific
rune."""
q = Query('''SELECT COUNT(rune) FROM rune_finds
WHERE player = %s''', player)
if rune:
q.append(' AND rune = %s', rune)
return q.first(cursor)
def player_count_br_enter(cursor, player, br=None):
"""Counts the number of times the player has entered branches (or a specific
branch."""
q = Query('''SELECT COUNT(br) FROM branch_enters
WHERE player = %s''', player)
if br:
q.append(' AND br = %s', br)
return q.first(cursor)
def player_count_br_end(cursor, player, br=None):
"""Counts the number of times the player has entered branches (or a specific
branch."""
q = Query('''SELECT COUNT(br) FROM branch_ends
WHERE player = %s''', player)
if br:
q.append(' AND br = %s', br)
return q.first(cursor)
def find_place(rows, player):
"""Given a list of one-tuple rows, returns the index at which the given
player name occurs in the one-tuples, or -1 if the player name is not
present in the list."""
if rows is None:
return -1
p = [r[0] for r in rows]
if player in p:
return p.index(player)
else:
return -1
def do_place_numeric(rows, callfn):
index = -1
rindex = -1
last_num = None
for r in rows:
rindex += 1
if last_num != r[1]:
index = rindex
last_num = r[1]
if not callfn(r, index):
break
def player_uniques_killed(c, player):
rows = query_rows(c, '''SELECT DISTINCT monster FROM kills_of_uniques
WHERE player = %s ORDER BY monster''',
player)
return [ row[0] for row in rows ]
def clan_uniques_killed(c, captain):
rows = query_rows(c, '''SELECT DISTINCT k.monster
FROM players p INNER JOIN kills_of_uniques k
ON p.name = k.player
WHERE p.team_captain = %s ORDER BY k.monster''',
captain)
return [ row[0] for row in rows ]
def uniques_unkilled(uniques_killed):
killset = set(uniques_killed)
return [ u for u in uniq.UNIQUES if u not in killset ]
def all_hs_combos(c):
return query_rows(c,
'''SELECT player, COUNT(*) FROM combo_highscores
GROUP BY player''')
def all_hs_combo_wins(c):
return query_rows(c,
'''SELECT player, COUNT(*) FROM game_combo_win_highscores
GROUP BY player''')
def all_hs_species(c):
return query_rows(c,
'''SELECT player, COUNT(*) FROM species_highscores
GROUP BY player''')
def all_hs_classes(c):
return query_rows(c,
'''SELECT player, COUNT(*) FROM class_highscores
GROUP BY player''')
def count_hs_combos(c, player):
return query_first(c,
'''SELECT COUNT(*) FROM combo_highscores
WHERE player = %s''',
player)
def count_hs_combo_wins(c, player):
return query_first(c,
'''SELECT COUNT(*) FROM game_combo_win_highscores
WHERE player = %s''',
player)
def count_hs_species(c, player):
return query_first(c,
'''SELECT COUNT(*) FROM species_highscores
WHERE player=%s ''',
player)
def game_hs_species(c, player):
return [ row_to_xdict(x) for x in
query_rows(c,
("SELECT " + ",".join(LOG_FIELDS)
+ " FROM species_highscores "
+ " WHERE player=%s ORDER BY score DESC, charabbrev"),
player) ]
def count_hs_classes(c, player):
return query_first(c,
'''SELECT COUNT(*) FROM class_highscores
WHERE player=%s''',
player)
def game_hs_classes(c, player):
return [ row_to_xdict(x) for x in
query_rows(c,
("SELECT " + ",".join(LOG_FIELDS)
+ " FROM class_highscores "
+ " WHERE player=%s ORDER BY score DESC, charabbrev"),
player) ]
###################################################################
# Super experimental team stuff. None of this is set in stone.
def drop_teams(c):
info("Drop teams")
query_do(c, 'DELETE FROM teams')
def team_exists(cursor, owner):
"""Returns the name of the team owned by 'owner', or None if there is no
team owned by her."""
row = query_row(cursor,
'''SELECT name FROM teams WHERE owner = %s''', owner)
if row is None:
return None
return row[0]
def _add_player_to_team(cursor, team_owner, player):
query_do(cursor,
'''UPDATE players SET team_captain = %s
WHERE name = %s''',
team_owner, player)
def wrap_transaction(fn):
"""Given a function, returns a function that accepts a cursor and arbitrary
arguments, calls the function with those args, wrapped in a transaction."""
def transact(cursor, *args):
result = None
cursor.execute('BEGIN;')
try:
result = fn(cursor, *args)
cursor.execute('COMMIT;')
except:
cursor.execute('ROLLBACK;')
raise
return result
return transact
def create_team(cursor, team, owner_name):
"""Creates a team with the given name, owned by the named player."""
loaddb.check_add_player(cursor, owner_name)
def _create_team(cursor):
query_do(cursor, '''INSERT INTO teams (owner, name) VALUES (%s, %s)
ON DUPLICATE KEY UPDATE name = %s''',
owner_name, team, team)
# Flush everyone from the team, in case a player was removed.
query_do(cursor, '''UPDATE players SET team_captain = NULL
WHERE team_captain = %s''',
owner_name)
# Add the team owner herself to the team.
_add_player_to_team(cursor, owner_name, owner_name)
wrap_transaction(_create_team)(cursor)
def get_team_captains(c):
return [r[0] for r in query_rows(c, 'SELECT owner FROM teams')]