-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwriteToSQLite.py
333 lines (312 loc) · 11.6 KB
/
writeToSQLite.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
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# @Time : 11/8/2016 8:12 PM
# @Author : Ann
# @Site :
# @File : writeToSQLite.py
# @Software: PyCharm
import json
import sqlite3
import yaml
import time
from os import listdir
import os
from collections import defaultdict
def _byteify(data, ignore_dicts = False):
"""
To convert any decoded JSON object from using unicode strings to UTF-8-encoded byte strings
:param data: raw data in json files
:param ignore_dicts:
:return: byte string data
"""
if isinstance(data, unicode):
return data.encode('utf-8')
if isinstance(data, list):
return [ _byteify(item, ignore_dicts=True) for item in data ]
if isinstance(data, dict) and not ignore_dicts:
return {
_byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)
for key, value in data.iteritems()
}
return data
def json_loads_byteified(json_text):
return _byteify(
json.loads(json_text, object_hook=_byteify),
ignore_dicts=True
)
# To write saved json data into SQLite database.
# STEP1: Create tables: user, thread and post.
# STEP2: Get data from files and insert it into target tables.
def createTables(conn, c):
"""
Create tables: user, thread and post.
:param conn: connection to target database
:param c: cursor of the connection
:return:
"""
#***********************************for users******************************#
c.execute('drop table if EXISTS user')
c.execute('''CREATE TABLE `user` \
( \
'photoUrl' TEXT, \
`courseId` TEXT, \
`userId` INTEGER, \
`id` TEXT, \
`learnerId` INTEGER, \
`courseRole` TEXT, \
`fullName` TEXT, \
'externalUserId' TEXT \
); ''')
# ***********************************for threads******************************#
c.execute('drop table if EXISTS thread')
c.execute('''CREATE TABLE `thread` \
('answerBadge' TEXT, \
'hasResolved' INTEGER, \
'instReplied' INTEGER, \
'totalAnswerCount' INTEGER, \
'isFollowing' INTEGER, \
'forumId' TEXT, \
`lastAnsweredAt` INTEGER, \
`topLevelAnswerCount` INTEGER, \
`isFlagged` INTEGER, \
'lastAnsweredBy' INTEGER, \
'state' TEXT, \
'followCount' INTEGER, \
'title' TEXT, \
'content' TEXT, \
'viewCount' INTEGER, \
'sessionId' TEXT, \
'creatorId' INTEGER, \
'isUpvoted' INTEGER, \
'id' TEXT, \
'courseId' TEXT, \
'threadId' TEXT, \
'createdAt' INTEGER, \
'upvoteCount' INTEGER \
); \
''')
# ***********************************for posts******************************#
c.execute('drop table if EXISTS post')
c.execute('''CREATE TABLE `post` \
('parentForumAnswerId' TEXT, \
'forumQuestionId' TEXT, \
'isFlagged' INTEGER, \
'order' INTEGER, \
'content' TEXT, \
'state' BLOB, \
'childAnswerCount' INTEGER, \
'creatorId' INTEGER, \
'isUpvoted' INTEGER, \
'id' TEXT, \
'courseId' TEXT, \
'postId' TEXT, \
'createdAt' INTEGER, \
'upvoteCount' INTEGER \
); \
''')
#***********************************for users******************************#
def getUsers(userFileName, conn, c):
filedata = open(userFileName,'r')
count = 0
cols_in_database = ['photoUrl','courseId','userId','id','learnerId','courseRole','fullName','externalUserId']
for eachline in filedata:
data = json.loads(json.dumps(eachline))
data = json_loads_byteified(data)
someitem = data.iterkeys()
columns = list(someitem)
if len(columns) != len(cols_in_database):
cols_notin_data = list(set(columns)^set(cols_in_database))
for i in xrange(len(cols_notin_data)):
data[cols_notin_data[i]] = ''
someitem = data.iterkeys()
columns = list(someitem)
else:
pass
query = 'insert or ignore into user values (?{1})'
query = query.format(",".join(columns), ",?" * (len(columns) - 1))
temp = []
for keys in data.iterkeys():
temp.append(data[keys])
values = tuple(temp)
c.execute(query,values)
count += 1
conn.commit()
#***********************************for threads******************************#
def getThread(threadFileName, conn,c ):
filedata = open(threadFileName,'r')
count = 0
cols_in_database = ['answerBadge','hasResolved','instReplied','totalAnswerCount','isFollowing', 'forumId' ,'lastAnsweredAt', 'topLevelAnswerCount', \
'isFlagged','lastAnsweredBy','state','followCount' ,'title','content','viewCount','sessionId','creatorId','isUpvoted', \
'id','courseId','threadId','createdAt','upvoteCount']
for eachline in filedata:
data = json.loads(json.dumps(eachline))
data = json_loads_byteified(data)
someitem = data.iterkeys()
columns = list(someitem)
if len(columns) != len(cols_in_database):
cols_notin_data = list(set(columns)^set(cols_in_database))
for i in xrange(len(cols_notin_data)):
if cols_notin_data[i] == 'courseId':
pass
elif cols_notin_data[i] == 'threadId':
pass
elif cols_notin_data[i] == 'title':
pass
elif cols_notin_data[i] == 'hasResolved':
pass
elif cols_notin_data[i] == 'instReplied':
pass
else:
data[cols_notin_data[i]] = ''
someitem = data.iterkeys()
columns = list(someitem)
else:
pass
query = 'insert or ignore into thread values (?{1})'
query = query.format(",".join(cols_in_database),",?" * (len(cols_in_database) - 1))
temp = []
for keys in data.iterkeys():
if keys == 'answerBadge':
if data['answerBadge'] == {}:
temp.append('')
temp.append(0)
temp.append(0)
else:
temp.append(data['answerBadge']['answerBadge'])
if data['answerBadge']['answerBadge'] == 'MENTOR_RESPONDED':
temp.append(1)
temp.append(1)
elif data['answerBadge']['answerBadge'] == 'INSTRUCTOR_RESPONDED':
temp.append(1)
temp.append(1)
elif data['answerBadge']['answerBadge'] == 'STAFF_RESPONDED':
temp.append(1)
temp.append(1)
else:
temp.append(0)
temp.append(0)
elif keys == 'content':
temp.append(data['content']['question'])
temp.append(data['content']['details']['definition']['value'])
elif keys == 'isFlagged':
if data['isFlagged'] == 'false':
temp.append(0)
else:
temp.append(1)
elif keys == 'isFollowing':
if data['isFollowing'] == 'false':
temp.append(0)
else:
temp.append(1)
elif keys == 'state':
if data['state'] == {}:
temp.append('')
else:
temp.append('edited')
elif keys == 'id':
id_str = data[keys]
userId,courseId,threadId = id_str.split('~')
new_str = courseId + '~' + threadId
temp.append(new_str)
temp.append(courseId)
temp.append(threadId)
else:
temp.append(data[keys])
values = tuple(temp)
c.execute(query,values)
count += 1
conn.commit()
#***********************************for posts******************************#
def getPost(postFileName, conn, c):
filedata = open(postFileName,'r')
count = 0
cols_in_database = ['parentForumAnswerId','forumQuestionId','isFlagged','order','content','state','childAnswerCount','creatorId','isUpvoted', \
'id','courseId','postId','createdAt','upvoteCount']
for eachline in filedata:
data = json.loads(json.dumps(eachline))
data = json_loads_byteified(data)
someitem = data.iterkeys()
columns = list(someitem)
if len(columns) != len(cols_in_database):
cols_notin_data = list(set(columns)^set(cols_in_database))
for i in xrange(len(cols_notin_data)):
if cols_notin_data[i] == 'courseId':
pass
elif cols_notin_data[i] == 'postId':
pass
else:
data[cols_notin_data[i]] = ''
someitem = data.iterkeys()
columns = list(someitem)
else:
pass
query = 'insert or ignore into post values (?{1})'
query = query.format(",".join(cols_in_database),",?" * (len(cols_in_database) - 1))
temp = []
for keys in data.iterkeys():
if keys == 'content':
temp.append(data['content']['definition']['value'])
elif keys == 'isFlagged':
if data['isFlagged'] == 'false':
temp.append(0)
else:
temp.append(1)
elif keys == 'isUpvoted':
if data['isUpvoted'] == 'false':
temp.append(0)
else:
temp.append(1)
elif keys == 'state':
if data['state'] == {}:
temp.append('')
else:
temp.append('edited')
elif keys == 'id':
id_str = data[keys]
userId,courseId,postId = id_str.split('~')
new_str = courseId + '~' + postId
temp.append(new_str)
temp.append(courseId)
temp.append(postId)
else:
temp.append(data[keys])
values = tuple(temp)
c.execute(query,values)
count += 1
conn.commit()
if __name__ == "__main__":
with open('config.yml') as f:
config = yaml.load(f)
dbPath = config['dbPath']
filePath = config['filePath']
f.close()
conn = sqlite3.connect(dbPath)
conn.text_factory = str
c = conn.cursor()
createTables(conn, c)
dirs = listdir(filePath)
count = 0
for dirName in dirs:
totalCourse = len(dirs)
count += 1
print "Processing %d...Total %d courses." %(count, totalCourse)
new_path = filePath + dirName + '/'
files = listdir(new_path)
userFileName = ''
threadFileName = ''
postFileName = ''
for file in files:
if file == 'users.json':
userFileName = new_path + file
#print userFileName
elif file == 'threads.json':
threadFileName = new_path + file
elif file == 'posts.json':
postFileName = new_path + file
getUsers(userFileName, conn, c)
print "Writing users OK!"
getThread(threadFileName, conn, c)
print "Writing threads OK!"
getPost(postFileName, conn, c)
print "Writing posts OK!"
conn.close()