-
Notifications
You must be signed in to change notification settings - Fork 0
/
database_maker_in_csv.py
223 lines (168 loc) · 8.72 KB
/
database_maker_in_csv.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
#!/usr/bin/python3
import mysql.connector, json, datetime, sys, os
from multiprocessing import Process, Queue
with open("config.json","r") as f:
CONFIG = json.load(f)
START_DATE = datetime.datetime.strptime(CONFIG["DB_MAKER"]["START_DATE"], "%Y-%m-%d") if CONFIG["DB_MAKER"]["START_DATE"] != None and CONFIG["DB_MAKER"]["START_DATE"] != "" else None
END_DATE = datetime.datetime.strptime(CONFIG["DB_MAKER"]["END_DATE"], "%Y-%m-%d") if CONFIG["DB_MAKER"]["END_DATE"] != None and CONFIG["DB_MAKER"]["END_DATE"] != "" else None
#YYYY-MM-DD HH:MM:SS datetime mysql format
READER_CORE_NUMBER = (int(os.cpu_count()/4) if int(os.cpu_count()/4) >= 1 else 1) if CONFIG["DB_MAKER"]["READER_CORE_NUMBER"] == "DEFAULT" else int(CONFIG["DB_MAKER"]["READER_CORE_NUMBER"])
WRITER_CORE_NUMBER = (int(os.cpu_count() - READER_CORE_NUMBER)) if CONFIG["DB_MAKER"]["WRITER_CORE_NUMBER"] == "DEFAULT" else int(CONFIG["DB_MAKER"]["WRITER_CORE_NUMBER"])
DOWNLOAD_PATH = CONFIG["INSTALLATION"]["DOWNLOAD_PATH"]
def datetime_parser(mydatetime, mysql=True):
if mydatetime == None: return mydatetime
return mydatetime.strftime("'%Y-%m-%d %H:%M:%S'") if mysql else mydatetime.strftime("%Y-%m-%d %H:%M:%S")
def rev_fetch_all(cursor,arraysize,table=None):
container = []
while True:
temp = cursor.fetchmany(arraysize)
if not temp:
break
container += temp
if table == "Post":
container = list(map(lambda x: "{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n".format(x[0],x[1],x[2],x[3],datetime_parser(x[4]),datetime_parser(x[5]),x[6],x[7],x[8],x[9],x[10],x[11],x[12],datetime_parser(x[13]),datetime_parser(x[14]),x[15],x[16],x[17],x[18],x[19],datetime_parser(x[20]),datetime_parser(x[21])), container))
elif table == "Comments":
container = list(map(lambda x: "{},{},{},{},{},{},{}\n".format(x[0],x[1],x[2],x[3],datetime_parser(x[4]),x[5],x[6]), container))
elif table == "PostLinks":
container = list(map(lambda x: "{},{},{},{},{}\n".format(x[0],datetime_parser(x[1]),x[2],x[3],x[4]), container))
elif table == "PostReferenceGH":
container = list(map(lambda x: "{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}".format(x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7],x[8],x[9],x[10],x[11],x[12],x[13],x[14]), container))
return container
def main_func(proc_number,questions_queue,answers_queue,comments_queue,postlinks_queue,postreferGH_queue,logger):
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "root",
database = "SistemiDistribuiti"
)
cursor = mydb.cursor()
BLOCK_DIM = 1000
questionIDs = []
multiplier = proc_number
while True:
record_from = BLOCK_DIM*multiplier
record_to = record_from + BLOCK_DIM
cursor.execute("SELECT * FROM Posts WHERE PostTypeId = 1 AND CreationDate BETWEEN {} AND {} LIMIT {}, {};".format(datetime_parser(START_DATE,True),datetime_parser(END_DATE,True),record_from,record_to))
questions = rev_fetch_all(cursor=cursor,arraysize=250,table="Post")
questionIDs += list(map(lambda x: (x.split(","))[0] ,questions))
questions_queue.put(questions)
if len(questions) < BLOCK_DIM:
break
else:
multiplier += WRITER_CORE_NUMBER
for i in range(READER_CORE_NUMBER):
questions_queue.put("DONE{}".format(i))
logger.write("\nPROCESS {} - has {} questions.\n".format(proc_number,len(questionIDs)))
answerIDs = []
limit= [0,BLOCK_DIM]
while True:
limited_ID_list = questionIDs[limit[0]:limit[1]]
limited_ID_list = (str(limited_ID_list))[1:-1]
if limited_ID_list != "":
cursor.execute("SELECT * FROM Posts WHERE ParentId IN ({})".format(limited_ID_list))
answers = rev_fetch_all(cursor=cursor,arraysize=250,table="Post")
answerIDs += list(map(lambda x: (x.split(","))[0] ,answers))
answers_queue.put(answers)
if len(limited_ID_list.split(",")) < BLOCK_DIM:
break
else:
limit[0]+=BLOCK_DIM
limit[1]+=BLOCK_DIM
for i in range(READER_CORE_NUMBER):
answers_queue.put("DONE{}".format(i))
questionIDs += answerIDs
answerIDs = None
del answerIDs
logger.write("\nPROCESS {} - has {} posts.\n".format(proc_number,len(questionIDs)))
limit= [0,BLOCK_DIM]
while True:
limited_ID_list = questionIDs[limit[0]:limit[1]]
limited_ID_list = (str(limited_ID_list))[1:-1]
if limited_ID_list != "":
cursor.execute("SELECT * FROM Comments WHERE PostId IN ({})".format(limited_ID_list))
comments = rev_fetch_all(cursor=cursor,arraysize=250,table="Comments")
comments_queue.put(comments)
if len(limited_ID_list.split(",")) < BLOCK_DIM:
break
else:
limit[0]+=BLOCK_DIM
limit[1]+=BLOCK_DIM
for i in range(READER_CORE_NUMBER):
comments_queue.put("DONE{}".format(i))
logger.write("\nPROCESS {} - has finished comments.\n".format(proc_number))
limit= [0,BLOCK_DIM]
while True:
limited_ID_list = questionIDs[limit[0]:limit[1]]
limited_ID_list = (str(limited_ID_list))[1:-1]
if limited_ID_list != "":
cursor.execute("SELECT * FROM PostLinks WHERE PostId IN ({})".format(limited_ID_list))
post_links = rev_fetch_all(cursor=cursor,arraysize=250,table="PostLinks")
postlinks_queue.put(post_links)
if len(limited_ID_list.split(",")) < BLOCK_DIM:
break
else:
limit[0]+=BLOCK_DIM
limit[1]+=BLOCK_DIM
for i in range(READER_CORE_NUMBER):
postlinks_queue.put("DONE{}".format(i))
logger.write("\nPROCESS {} - has finished post links.\n".format(proc_number))
limit= [0,BLOCK_DIM]
while True:
limited_ID_list = questionIDs[limit[0]:limit[1]]
limited_ID_list = (str(limited_ID_list))[1:-1]
if limited_ID_list != "":
cursor.execute("SELECT * FROM PostReferenceGH WHERE PostId IN ({})".format(limited_ID_list))
post_GH = rev_fetch_all(cursor=cursor,arraysize=250,table="PostReferenceGH")
postreferGH_queue.put(post_GH)
if len(limited_ID_list.split(",")) < BLOCK_DIM:
break
else:
limit[0]+=BLOCK_DIM
limit[1]+=BLOCK_DIM
for i in range(READER_CORE_NUMBER):
postreferGH_queue.put("DONE{}".format(i))
logger.write("\nPROCESS {} - has finished PostReferenceGH.\n".format(proc_number))
def read_queues(questions_queue,answers_queue,comments_queue,postlinks_queue,postreferGH_queue,logger,proc_number):
queues=[questions_queue,answers_queue,comments_queue,postlinks_queue,postreferGH_queue]
queues_obj = ["questions","answers","comments","postlinks","postreferGH"]
container = []
for i in range(len(queues)):
done = 0
logger.write("\nREADER {} - is starting iterating {}\n".format(proc_number, queues_obj[i]))
while True:
objs = queues[i].get()
if str(objs).startswith("DONE"):
if objs == "DONE{}".format(proc_number):
done += 1
if done >= WRITER_CORE_NUMBER:
break
else:
queues[i].put(objs)
continue
else:
container += objs
"".join(container)
logger.write("\nREADER {} - is start saving to csv file: {}.csv\n".format(proc_number, queues_obj[i]))
with open("{}/{}.csv".format(DOWNLOAD_PATH,queues_obj[i]),"w") as f:
f.write(container)
container = None
if __name__ == '__main__':
print("Process writer number: {}, Process reader number: {}".format(WRITER_CORE_NUMBER,READER_CORE_NUMBER))
process_pool = []
questions_queue = Queue()
answers_queue = Queue()
comments_queue = Queue()
postlinks_queue = Queue()
postreferGH_queue = Queue()
for i in range(WRITER_CORE_NUMBER):
print("Process {} started..\n".format(i))
p = Process(target=main_func, args=(i,questions_queue,answers_queue,comments_queue,postlinks_queue,postreferGH_queue,sys.stdout))
process_pool.append(p)
p.start()
for i in range(READER_CORE_NUMBER):
print("Process {} reader started..\n".format(i))
reader = Process(target=read_queues, args=(questions_queue,answers_queue,comments_queue,postlinks_queue,postreferGH_queue,sys.stdout,i))
process_pool.append(reader)
reader.start()
for p in process_pool:
p.join()