-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdb_init.py
100 lines (79 loc) · 2.5 KB
/
db_init.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
import os
import sys
import pymongo
import tornado.gen
import tornado.ioloop
from settings import db, BOT_TOKEN
@tornado.gen.coroutine
def setup_bot():
data = {
'token': BOT_TOKEN,
'login': 'stxnext',
'data': {
'name': 'STX Next Bot',
'email': '[email protected]',
}
}
bot_user = yield db.users.find_one({'login': 'stxnext'})
if bot_user is not None:
data['_id'] = bot_user['_id']
yield db.users.save(data)
@tornado.gen.coroutine
def ensure_indexes():
yield db.users.ensure_index([
('token', pymongo.HASHED),
])
yield db.users.ensure_index([
('login', pymongo.HASHED),
])
yield db.results.ensure_index([
('login', pymongo.HASHED),
])
yield db.results.ensure_index([
('board_size', pymongo.HASHED),
])
yield db.results.ensure_index([
('score', pymongo.HASHED),
])
@tornado.gen.coroutine
def migrate_names():
# find mapping between user name and user login
users = {}
cursor = db.users.find()
while (yield cursor.fetch_next):
user = cursor.next_object()
data = user.get('data')
if data and data.get('name'):
users[data['name']] = user['login']
# replace name with login in all stored game rooms
to_save = []
cursor = db.rooms.find()
while (yield cursor.fetch_next):
game_room = cursor.next_object()
if game_room.get('results'):
for item in game_room['results']:
if 'name' in item:
name = item.pop('name')
item['login'] = users.get(name, name)
to_save.append(game_room)
for game_room in to_save:
yield db.rooms.save(game_room)
# replace name with login in hall of fame data, remove duplicates
to_save = []
to_remove = []
cursor = db.results.find()
while (yield cursor.fetch_next):
result = cursor.next_object()
if result['login'] in users:
result['login'] = users[result['login']]
to_save.append(result)
elif '(' in result['login']:
to_remove.append(result['_id'])
for result in to_save:
yield db.results.save(result)
for _id in to_remove:
yield db.results.remove({'_id': _id})
if __name__ == '__main__':
tornado.ioloop.IOLoop.current().run_sync(ensure_indexes)
tornado.ioloop.IOLoop.current().run_sync(setup_bot)
tornado.ioloop.IOLoop.current().run_sync(migrate_names)