/
database_creation.py
216 lines (151 loc) · 5.39 KB
/
database_creation.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
import requests
from bs4 import BeautifulSoup
import json
import re
import pandas as pd
import numpy as np
import datetime
from psycopg2 import connect
countries = [
'us','brazil','russia','spain',
'italy','france','germany',
'turkey','india','iran','peru',
'canada','chile','china','mexico',
'saudi-arabia','pakistan','belgium',
'qatar', 'bangladesh',
'belarus', 'ecuador', 'sweden'
]
def connect_database(dbname, user='hp', password='test1234', host='127.0.0.1', autocommit=False):
"""
Connect to the PostgreSQL database based on the parameters.
parameters:
dbname: str.
Name of the database.
user: str.
Name of the user. Default hp.
password: str.
Password for the user to connect.
host: str.
The IP address of the hosted database. Default 127.0.0.1 (localhost).
autocommit: Boolean.
Set autocommit to True or False. Default False
returns:
conn: connection object.
A connection object to the database.
"""
conn = connect("dbname="+dbname+" user="+user+" password="+password+" host="+host)
conn.autocommit = True
return conn
def create_country_relations(conn):
"""
Create relations for every country in the database, for covid-19 statistics.
parameters:
conn: connection object.
A connection object to the database.
returns: bool.
Boolean.
"""
cursor = conn.cursor()
for country in countries:
data = pd.read_csv('./Data/covid19_'+country+'_stats.csv')
country = re.sub('-','',country)
query = "DROP TABLE IF EXISTS "+country+"_stats;"
cursor.execute(query)
query = """
CREATE TABLE """+country+"""_stats (
date DATE PRIMARY KEY,
total_cases INT,
daily_cases INT,
active_cases INT,
total_deaths INT,
daily_deaths INT
);"""
cursor.execute(query)
for ind,row in data.iterrows():
row = row.fillna(0)
query = """
INSERT INTO """+country+"""_stats
VALUES (
'"""+row.date+"""',
"""+str(row.total_cases)+""",
"""+str(row.daily_cases)+""",
"""+str(row.active_cases)+""",
"""+str(row.total_deaths)+""",
"""+str(row.daily_deaths)+"""
);"""
cursor.execute(query)
print('Table successfully created: ',country+'_stats')
return True
def create_overall_relation(conn):
"""
Create the relation containing overall statistics for all the countries.
parameters:
conn: connection object.
A connection object to the database.
returns: bool.
Boolean.
"""
cursor = conn.cursor()
data = pd.read_csv('./Data/covid19_overall_stat.csv')
query = "DROP TABLE IF EXISTS overall_stats;"
cursor.execute(query)
query = """
CREATE TABLE overall_stats (
country VARCHAR(25),
total_cases BIGINT,
total_deaths BIGINT,
total_recoveries BIGINT
);
"""
cursor.execute(query)
for ind,row in data.iterrows():
row = row.fillna(0)
row.country = row.country.replace(' ','')
query = """
INSERT INTO overall_stats VALUES (
'"""+row.country+"""',
"""+str(row.total_cases)+""",
"""+str(row.total_deaths)+""",
"""+str(row.total_recoveries)+"""
);"""
cursor.execute(query)
print("Table successfully created")
return True
def update_database(conn):
"""
Updates the database with the daily updates on statistics for countries.
parameters:
conn: connection object.
A connection object to the database.
returns: bool.
Boolean.
"""
cursor = conn.cursor()
for country in countries:
query = "SELECT date FROM "+country.replace('-','')+"_stats ORDER BY date DESC LIMIT 1;"
cursor.execute(query)
last_date = cursor.fetchone()[0]
if (pd.to_datetime(last_date).date() != datetime.datetime.today().date()):
data = pd.read_csv('./Data/covid19_'+country+'_stats.csv')
update = data.iloc[-1].fillna(0)
if pd.to_datetime(update.date).date() != datetime.datetime.today().date():
continue
query = """
INSERT INTO """+country.replace('-','')+"""_stats
VALUES (
'"""+update.date+"""',
"""+str(update.total_cases)+""",
"""+str(update.daily_cases)+""",
"""+str(update.active_cases)+""",
"""+str(update.total_deaths)+""",
"""+str(update.daily_deaths)+"""
);
"""
cursor.execute(query)
print("Table",country+"_stats updated")
return True
if __name__ == '__main__':
conn = connect_database('covid19_stats', autocommit= True)
create_country_relations(conn)
create_overall_relation(conn)
update_database(conn)