1
1
import MySQLdb
2
2
import yaml
3
+ import progressbar
4
+ from pymongo import MongoClient
3
5
4
6
5
7
def load_configuration ():
@@ -10,11 +12,75 @@ def load_configuration():
10
12
11
13
def get_cursor (dbconf ):
12
14
db = MySQLdb .connect (host = dbconf .get ('hostname' ), user = dbconf .get ('username' ), passwd = dbconf .get ('password' ),
13
- db = dbconf .get ('database' ))
14
- return db .cursor ()
15
+ db = dbconf .get ('database' ), charset = 'utf8' )
16
+ return db .cursor (MySQLdb .cursors .DictCursor )
17
+
18
+
19
+ def get_legacy_activities (dbcursor ):
20
+ query = """
21
+ SELECT
22
+ u.id AS user_id,
23
+ a.date AS created_at,
24
+ IF (a.type != 7, p.username, NULL) AS performed_by,
25
+ IF (a.type != 7, up.value, NULL) AS performer_avatar,
26
+ b.name AS badge_name,
27
+ b.image AS badge_image,
28
+ CASE
29
+ WHEN a.type = 1 THEN 'notification'
30
+ WHEN a.type = 2 THEN 'like'
31
+ WHEN a.type = 3 THEN 'comment'
32
+ WHEN a.type = 4 THEN 'repost'
33
+ WHEN a.type = 5 THEN 'follow'
34
+ WHEN a.type = 6 THEN 'mention'
35
+ WHEN a.type = 7 THEN 'badge'
36
+ END AS type,
37
+ IF(a.type IN (2, 3, 4, 6, 7), a.related_id, NULL) AS post_id,
38
+ pp.value AS post_image,
39
+ a.clicked AS clicked
40
+ FROM activities a
41
+ LEFT JOIN users p ON a.performer_id = p.id
42
+ LEFT JOIN users u ON a.user_id = u.id
43
+ LEFT JOIN users_parameters up ON up.user_id = p.id AND up.parameter_id = 4
44
+ LEFT JOIN posts_parameters pp ON pp.post_id = a.related_id AND pp.parameter_id = 6 AND a.type IN (2, 3, 4, 6, 7)
45
+ LEFT JOIN badges b ON b.id = a.performer_id AND a.type = 7
46
+ """
47
+ dbcursor .execute (query )
48
+ return dbcursor .fetchall ()
49
+
50
+
51
+ def get_collection (dbconf ):
52
+ client = MongoClient (dbconf .get ('hostname' ), dbconf .get ('port' ))
53
+ db = client [dbconf .get ('database' )]
54
+ db .drop_collection ('activities' )
55
+ db .create_collection ('activities' )
56
+ return db .activities
15
57
16
58
17
59
config = load_configuration ()
18
60
cursor = get_cursor (config .get ('mysql' , {}))
61
+ legacy_activities = get_legacy_activities (cursor )
62
+ collection = get_collection (config .get ('mongo' , {}))
63
+ bar = progressbar .ProgressBar ()
64
+
65
+ for row in bar (legacy_activities ):
66
+ activity = {
67
+ 'user_id' : row ['user_id' ],
68
+ 'created_at' : row ['created_at' ],
69
+ 'type' : row ['type' ],
70
+ 'performed_by' : row ['performed_by' ],
71
+ 'performer_avatar' : row ['performer_avatar' ]
72
+ }
73
+
74
+ if row ['type' ] in ('like' , 'comment' , 'repost' , 'mention' ):
75
+ activity ['post_id' ] = row ['post_id' ]
76
+ activity ['post_image' ] = row ['post_image' ]
77
+
78
+ if row ['type' ] == 'badge' :
79
+ activity ['badge_name' ] = row ['badge_name' ]
80
+ activity ['badge_image' ] = row ['badge_image' ]
81
+
82
+ activity ['clicked' ] = True if row ['clicked' ] == 1 else False
19
83
84
+ collection .insert_one (activity )
20
85
86
+ print 'Migration successful'
0 commit comments