-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAssignment1.py
229 lines (193 loc) · 8.53 KB
/
Assignment1.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
#!/usr/bin/python2.7
#
# Assignment1 Library
#
import psycopg2
import os
import sys
DATABASE_NAME = 'dds_assignment'
RANGE_TABLE_PREFIX = 'RangeRatingsPart'
RROBIN_TABLE_PREFIX = 'RoundRobinRatingsPart'
def getOpenConnection(user='postgres', password='sa', dbname='postgres'):
return psycopg2.connect("dbname='" + dbname + "' user='" + user + "' host='localhost' password='" + password + "'")
def createDB(dbname=DATABASE_NAME):
"""
We create a DB by connecting to the default user and database of Postgres
The function first checks if an existing database exists for a given name, else creates it.
:return:None
"""
# Connect to the default database
con = getOpenConnection(dbname='postgres')
con.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
# Check if an existing database with the same name exists
cur.execute('SELECT COUNT(*) FROM pg_catalog.pg_database WHERE datname=\'%s\'' % (dbname,))
count = cur.fetchone()[0]
if count == 0:
cur.execute('CREATE DATABASE %s' % (dbname,)) # Create the database
else:
print 'A database named {0} already exists'.format(dbname)
# Clean up
cur.close()
con.commit()
con.close()
def loadRatings(ratingstablename, ratingsfilepath, openconnection):
cur = openconnection.cursor()
cur.execute("DROP TABLE IF EXISTS " + ratingstablename)
cur.execute(
"CREATE TABLE " + ratingstablename + " (UserID INT, temp1 VARCHAR(10), MovieID INT , temp3 VARCHAR(10), Rating REAL, temp5 VARCHAR(10), Timestamp INT)")
loadout = open(ratingsfilepath, 'r')
cur.copy_from(loadout, ratingstablename, sep=':',
columns=('UserID', 'temp1', 'MovieID', 'temp3', 'Rating', 'temp5', 'Timestamp'))
cur.execute(
"ALTER TABLE " + ratingstablename + " DROP COLUMN temp1, DROP COLUMN temp3,DROP COLUMN temp5, DROP COLUMN Timestamp")
cur.close()
openconnection.commit()
def rangePartition(ratingstablename, numberofpartitions, openconnection):
name = RANGE_TABLE_PREFIX
try:
cursor = openconnection.cursor()
cursor.execute("select * from information_schema.tables where table_name='%s'" % ratingstablename)
if not bool(cursor.rowcount):
print "Please Load Ratings Table first!!!"
return
cursor.execute(
"CREATE TABLE IF NOT EXISTS RangeRatingsMetadata(PartitionNum INT, MinRating REAL, MaxRating REAL)")
MinRating = 0.0
MaxRating = 5.0
step = (MaxRating - MinRating) / (float)(numberofpartitions)
i = 0;
while i < numberofpartitions:
newTableName = name + `i`
cursor.execute("CREATE TABLE IF NOT EXISTS %s(UserID INT, MovieID INT, Rating REAL)" % (newTableName))
i += 1;
i = 0;
while MinRating < MaxRating:
lowerLimit = MinRating
upperLimit = MinRating + step
if lowerLimit < 0:
lowerLimit = 0.0
if lowerLimit == 0.0:
cursor.execute(
"SELECT * FROM %s WHERE Rating >= %f AND Rating <= %f" % (ratingstablename, lowerLimit, upperLimit))
rows = cursor.fetchall()
newTableName = name + `i`
for row in rows:
cursor.execute("INSERT INTO %s(UserID, MovieID, Rating) VALUES(%d, %d, %f)" % (
newTableName, row[0], row[1], row[2]))
if lowerLimit != 0.0:
cursor.execute(
"SELECT * FROM %s WHERE Rating > %f AND Rating <= %f" % (ratingstablename, lowerLimit, upperLimit))
rows = cursor.fetchall()
newTableName = name + `i`
for row in rows:
cursor.execute("INSERT INTO %s(UserID, MovieID, Rating) VALUES(%d, %d, %f)" % (
newTableName, row[0], row[1], row[2]))
cursor.execute(
"INSERT INTO RangeRatingsMetadata (PartitionNum, MinRating, MaxRating) VALUES(%d, %f, %f)" % (
i, lowerLimit, upperLimit))
MinRating = upperLimit
i += 1;
openconnection.commit()
except psycopg2.DatabaseError, e:
if openconnection:
openconnection.rollback()
print 'Error %s' % e
sys.exit(1)
except IOError, e:
if openconnection:
openconnection.rollback()
print 'Error %s' % e
sys.exit(1)
finally:
if cursor:
cursor.close()
def roundRobinPartition(ratingstablename, numberofpartitions, openconnection):
name = RROBIN_TABLE_PREFIX
try:
cursor = openconnection.cursor()
cursor.execute("select * from information_schema.tables where table_name='%s'" % (ratingstablename))
if not bool(cursor.rowcount):
print "Please Load Ratings Table first!!!"
return
cursor.execute("CREATE TABLE IF NOT EXISTS RoundRobinRatingsMetadata(PartitionNum INT, TableNextInsert INT)")
x = 0
upperLimit = numberofpartitions
cursor.execute("SELECT * FROM %s" % ratingstablename)
rows = cursor.fetchall()
lastInserted = 0
for row in rows:
if x < upperLimit:
newTableName = name + `x`
cursor.execute("CREATE TABLE %s(UserID INT, MovieID INT, Rating REAL)" % (newTableName))
cursor.execute("INSERT INTO %s(UserID, MovieID, Rating) VALUES(%d, %d, %f)" % (
newTableName, row[0], row[1], row[2]))
x += 1
lastInserted = lastInserted + 1
y = (lastInserted % numberofpartitions)
else:
newTableName = name + `y`
cursor.execute("INSERT INTO %s(UserID, MovieID, Rating) VALUES(%d, %d, %f)" % (
newTableName, row[0], row[1], row[2]))
lastInserted = (lastInserted + 1) % numberofpartitions
y = lastInserted
cursor.execute("INSERT INTO RoundRobinRatingsMetadata (PartitionNum, TableNextInsert) VALUES(%d,%d)" % (
numberofpartitions, lastInserted))
openconnection.commit()
except psycopg2.DatabaseError, e:
if openconnection:
openconnection.rollback()
print 'Error %s' % e
sys.exit(1)
except IOError, e:
if openconnection:
openconnection.rollback()
print 'Error %s' % e
sys.exit(1)
finally:
if cursor:
cursor.close()
def deleteTables(ratingstablename, openconnection):
try:
cursor = openconnection.cursor()
if ratingstablename.upper() == 'ALL':
cursor.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'")
tables = cursor.fetchall()
for table_name in tables:
cursor.execute('DROP TABLE %s CASCADE' % (table_name[0]))
else:
cursor.execute('DROP TABLE %s CASCADE' % (ratingstablename))
openconnection.commit()
except psycopg2.DatabaseError, e:
if openconnection:
openconnection.rollback()
print 'Error %s' % e
sys.exit(1)
except IOError, e:
if openconnection:
openconnection.rollback()
print 'Error %s' % e
sys.exit(1)
finally:
if cursor:
cursor.close()
def roundrobininsert(ratingstablename, userid, itemid, rating, openconnection):
cur = openconnection.cursor()
cur.execute("insert into {0} values({1}, {2}, {3})".format(ratingstablename, userid, itemid, rating))
cur.execute("select count(table_name) from information_schema.tables where table_name like 'rrobin_part%'")
N = int(cur.fetchone()[0])
cur.execute("select count(*) from {0}".format(ratingstablename))
count = int(cur.fetchone()[0])
cur.execute('insert into rrobin_part{0} values ({1}, {2}, {3})'.format(count % N - 1, userid, itemid, rating))
cur.close()
def rangeinsert(ratingstablename, userid, itemid, rating, openconnection):
cur = openconnection.cursor()
cur.execute("insert into {0} values({1}, {2}, {3})".format(ratingstablename, userid, itemid, rating))
cur.execute("select count(table_name) from information_schema.tables where table_name like 'range_part%'")
N = int(cur.fetchone()[0])
interval = 5.0 / N
partition_id = int(rating / interval)
if abs(partition_id * interval - rating) < 0.0000000001 and partition_id > 0:
partition_id -= 1
cur.execute('insert into range_part{0} values ({1}, {2}, {3})'.format(partition_id, userid, itemid, rating))
cur.close()