-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
388 lines (388 loc) · 17.8 KB
/
Copy pathdatabase.py
File metadata and controls
388 lines (388 loc) · 17.8 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import sys
def create(database, tableName, columns): #Creates us a table with the given table name and column names and record them into database
if tableName in database:
print(f"Table '{tableName}' already exists.")
return
database[tableName] = {"columns": columns,"rows": []} #Records the datas in a dictionary that will help us in further functions
print(f"###################### CREATE #########################")
print(f"Table '{tableName}' created with columns: {columns}")
print("#"*55)
def insert(database, tableName, datas): #Inserts the given datas to the table
datas = [data.strip() for data in datas]
row = (list(datas))
if tableName not in database:
print("\n"f"###################### INSERT #########################")
print(f"Table {tableName} not found")
print(f"Inserted into '{tableName}': {row}")
return #Gives us informative message about the situation where table name is not registered in database which means there is no table named like that
table = database[tableName]
columns = table["columns"]
table['rows'].append(row)
if len(datas) != len(columns): #Checks the amount of datas which are given and compares the amount of it with columns
print(f"Column count does not match value count for table '{tableName}'.")
print(f"Expected columns: {len(columns)} | Provided values: {len(datas)}")
return
print("\n"f"###################### INSERT #########################")
print(f"Inserted into '{tableName}': {row}")
print("\n"f"Table: {tableName}")
printTable(table['columns'], table['rows'])
print("#" * 55)
def condDetect(conditions): #Helps us to the detect the conditions that are given with "WHERE" phrase
conDict = {}
conditions = conditions.strip('{}').strip()
if not conditions:
return conDict
try:
pairs = conditions.split(',')
for pair in pairs:
key, value = pair.split(':')
key = key.strip().strip('"').strip("'")
value = value.strip().strip('"').strip("'")
conDict[key] = value #Separates the WHERE condition and appends them as key-value pair to our cond. dict.
except:
print(f"Defective WHERE condition '{conditions}'")
return None
return conDict
def select(database, tableName, selectedColumns, conditions): #Shows us the datas that matches with the given conditions from table
conDict = condDetect(conditions)
if tableName not in database:
print("\n"f"###################### SELECT #########################") #The situation about table name
print(f"Table {tableName} not found")
print(f"Condition: {conDict}")
print(f"Select result from '{tableName}': None")
print("#" * 55)
return
table = database[tableName]
allColumns = table['columns']
rows = table['rows']
for column in selectedColumns: #The situation about columns in table
if column not in allColumns:
print("\n"f"###################### SELECT #########################")
print(f"Column {column} does not exist")
print(f"Condition: {conDict}")
print(f"Select result from '{tableName}': None")
print("#" * 55)
return
conDict = condDetect(conditions)
if conDict is None: #No given condition
return
for column in conDict.keys(): #The situation about columns in WHERE clause
if column not in allColumns:
print("\n"f"###################### SELECT #########################")
print(f"Column {column} does not exist")
print(f"Condition: {conDict}")
print(f"Select result from '{tableName}': None")
print("#" * 55)
return
matchRows = []
for row in rows: #Checks the rows,finds the matching ones with the WHERE clause, add them into a tuple
rowDict = {}
for index in range(len(allColumns)):
colName = allColumns[index]
selData = row[index]
rowDict[colName] = selData
match = True
for key, value in conDict.items():
if str(rowDict.get(key)) != str(value):
match = False
break
if match:
matchRows.append(row)
colIndexes = []
for col in selectedColumns:
colIndexes.append(allColumns.index(col))
selectRows = []
for row in matchRows:
selectedData = []
for index in colIndexes:
selData = row[index]
selectedData.append(selData)
selectedRow = tuple(selectedData)
selectRows.append(selectedRow)
print("\n"f"###################### SELECT #########################")
print(f"Condition: {conditions}")
print(f"Select result from '{tableName}': {selectRows}")
print("#" * 55)
def update(database, tableName, updates, conditions): #Function that updates the table according to WHERE phrase
conDict = condDetect(conditions)
updateDict = condDetect(updates)
if tableName not in database:
print("\n"f"###################### UPDATE #########################")
print(f"Updated '{tableName}' with {updateDict} where {conDict}")
print(f"Table {tableName} not found")
print("0 rows updated.")
print("#" * 55)
return
table = database[tableName]
allColumns = table['columns']
rows = table['rows']
for column in updateDict.keys(): #The situation about columns in table
if column not in allColumns:
print("\n"f"###################### UPDATE #########################")
print(f"Updated '{tableName}' with {updateDict} where {conDict}")
print(f"Column {column} does not exist")
print("0 rows updated.")
print("\n"f"Table: {tableName}")
printTable(allColumns, rows)
print("#" * 55)
return
for column in conDict.keys(): #The situation about columns in WHERE clause
if column not in allColumns:
print("\n"f"###################### UPDATE #########################")
print(f"Updated '{tableName}' with {updateDict} where {conDict}")
print(f"Column {column} does not exist")
print("0 rows updated.")
print("\n"f"Table: {tableName}")
printTable(allColumns, rows)
print("#" * 55)
return
updatedCount = 0
for index, row in enumerate(rows): #Checks the rows,finds the matching ones with the WHERE clause, updates them and counts the number of how many updated
rowDict = {}
for index in range(len(allColumns)):
colName = allColumns[index]
selData = row[index]
rowDict[colName] = selData
match = True
for key, value in conDict.items():
if str(rowDict.get(key)) != str(value):
match = False
break
if match:
updatedRow = []
for data in row:
updatedRow.append(data)
for key, value in updateDict.items():
colIndex = allColumns.index(key)
updatedRow[colIndex] = value
rows[index] = tuple(updatedRow)
updatedCount += 1
print("\n"f"###################### UPDATE #########################")
print(f"Updated '{tableName}' with {updateDict} where {conDict}")
print(f"{updatedCount} rows updated.")
print("\n"f"Table: {tableName}")
printTable(table['columns'], table['rows'])
print("#" * 55)
def delete(database, tableName, conditions):#Function that deletes data from table according to WHERE phrase
conDict = condDetect(conditions)
if tableName not in database:
print("\n"f"###################### DELETE #########################")#The situation about table name
print(f"Deleted from '{tableName}' where {conDict}.")
print(f"Table {tableName} not found")
print("0 rows deleted.")
print("#" * 55)
return
table = database[tableName]
allColumns = table['columns']
rows = table['rows']
for column in conDict.keys():
if column not in allColumns:
print("\n"f"###################### DELETE #########################")#The situation about columns in table
print(f"Deleted from '{tableName}' where {conDict}")
print(f"Column {column} does not exist")
print("0 rows deleted.")
print("\n"f"Table: {tableName}")
printTable(allColumns, rows)
print("#" * 55)
return
rowCount = len(rows)
newRows = []
for row in rows: #Checks the rows and finds the one's that doesn't match with WHERE clause
rowDict = {}
for index in range(len(allColumns)):
rowDict[allColumns[index]] = row[index]
match = True
for key, value in conDict.items():
if key in rowDict:
if str(rowDict.get(key)).strip() != str(value).strip():
match = False
break
if not match:
newRows.append(row)
deletedCount = rowCount - len(newRows)
table['rows'] = newRows
if conDict is None:
deletedCount = len(rows)
rows.clear()
print("\n"f"###################### DELETE #########################") #No given conditions
print(f"Deleted all rows from '{tableName}'")
print(f"{deletedCount} rows deleted.")
print("#" * 55)
return
else:
print("\n"f"###################### DELETE #########################")
print(f"Deleted from '{tableName}' where {conDict}.")
print(f"{deletedCount} rows deleted.")
print("\n"f"Table: {tableName}")
printTable(allColumns, newRows)
print("#" * 55)
return
def count(database, tableName, conditions): #Function that counts datas which matches with the WHERE phrase
conDict = condDetect(conditions)
if tableName not in database: #The situation about table name
print("\n"f"###################### COUNT #########################")
print(f"Table {tableName} not found")
print(f"Total number of entries in '{tableName}' is 0")
print("#" * 55)
return
table = database[tableName]
allColumns = table['columns']
rows = table['rows']
if conditions is None: #No given conditions
totalCount = len(rows)
print("\n"f"###################### COUNT #########################")
print(f"Total number of entries in '{tableName}' is {totalCount}")
print("#" * 55)
return totalCount
for column in conDict.keys():
if column not in allColumns: #The situation about columns in table
print("\n"f"###################### COUNT #########################")
print(f"Column '{column}' does not exist")
print(f"Total number of entries in '{tableName}' is 0")
print("#" * 55)
return
count = 0
for row in rows: #Checking rows and counts how many rows matches with the WHERE clause
rowDict = {}
for index in range(len(allColumns)):
rowDict[allColumns[index]] = row[index]
match = True
for key, value in conDict.items():
if key in rowDict:
if str(rowDict.get(key)).strip() != str(value).strip():
match = False
break
if match:
count += 1
print("\n"f"###################### COUNT #########################")
print(f"Count: {count}")
print(f"Total number of entries in '{tableName}' is {count}")
print("#"*55)
return count
def join(database, table1Name, table2Name, colName): #Function that joins two tables into one
if table1Name not in database: #Situation about the first table's name
print("\n"f"###################### JOIN #########################")
print(f"Join tables {table1Name} and {table2Name}")
print(f"Table {table1Name} does not exist")
print("#"*55)
return
if table2Name not in database: #Situation about the second table's name
print("\n"f"###################### JOIN #########################")
print(f"Join tables {table1Name} and {table2Name}")
print(f"Table {table2Name} does not exist")
print("#"*55)
return
table1 = database[table1Name]
table2 = database[table2Name]
table1Col = table1['columns'] #Pulling data from database
table2Col = table2['columns']
table1Rows = table1['rows']
table2Rows = table2['rows']
if colName not in table1Col or colName not in table2Col: #The situation about columns in tables
print("\n"f"###################### JOIN #########################")
print(f"Join tables {table1Name} and {table2Name}")
print(f"Column {colName} does not exist")
print("#"*55)
return
index1 = table1Col.index(colName)
index2 = table2Col.index(colName)
joinedCol = table1Col + table2Col
joinedRows = []
lenJoinedRows = len(joinedRows)
for row1 in table1Rows:
for row2 in table2Rows:
if str(row1[index1]) == str(row2[index2]): #Checks matching rows
joinedRows.append(row1 + row2)
lenJoinedRows = len(joinedRows)
print("\n"f"###################### JOIN #########################")
print(f"Join tables {table1Name} and {table2Name}")
print(f"Join result ({lenJoinedRows} rows):")
print("\n""Table: Joined Table")
printTable(joinedCol, joinedRows)
print("#" * 55)
return
def printTable(columns, rows): #Prints us table
if len(rows) == 0: #No rows situation
print("There are no rows in the table.")
return
colWidth = []
for index in range(len(columns)): #Finds max width for each column and sotre them in a list
max_width = len(columns[index])
for row in rows:
max_width = max(max_width, len(str(row[index])))
colWidth.append(max_width)
print('+' + '+'.join(['-' * (width + 2) for width in colWidth]) + '+') #Top border of the table
header = '| ' + ' | '.join([columns[index].ljust(colWidth[index]) for index in range(len(columns))]) + ' |' #Column names row(Header)
print(header)
print('+' + '+'.join(['-' * (width + 2) for width in colWidth]) + '+') #Border under the header
for row in rows:
line = '| ' + ' | '.join([str(row[index]).ljust(colWidth[index]) for index in range(len(row))]) + ' |' #ljust(left-justified) func helps us the match the width of the column with the max length
print(line) #Prints each row of table
print('+' + '+'.join(['-' * (width + 2) for width in colWidth]) + '+') #Bottom border
def main():
database = {}
inpFile = sys.argv[1]
with open(inpFile, "r") as commandFile:
data = commandFile.readlines()
for index, commands in enumerate(data):
commands = commands.strip()
if not commands:
continue
parts = commands.split(" ", 2)
command = parts[0]
if command == "CREATE_TABLE":
try:
if index != 0:
print("\n")
tableName = parts[1]
columns = [column.strip() for column in parts[2].split(",")]
create(database, tableName, columns)
except:
print(f"Invalid CREATE_TABLE command syntax in '{commands}'")
elif command == "INSERT":
try:
tableName = parts[1]
datas = [data.strip() for data in parts[2].split(",")]
insert(database, tableName, datas)
except:
print(f"Invalid INSERT command syntax in '{commands}'")
elif command == "SELECT":
try:
tableName, colandcond = parts[1], parts[2]
basePart, condPart = colandcond.split("WHERE")
selectedCol = [data.strip() for data in basePart.split(",")]
cond = condPart.strip()
select(database, tableName, selectedCol, cond)
except:
print(f"Invalid SELECT command syntax in '{commands}'")
elif command == "UPDATE":
tableName = parts[1]
updates, cond = parts[2].split("WHERE")
update(database, tableName, updates.strip(), cond.strip())
elif command == "DELETE":
try:
if "WHERE" in parts[2]:
tableName, condPart = parts[1], parts[2].split("WHERE", 1)[1].strip()
else:
tableName, condPart = parts[1], ""
delete(database, tableName, condPart)
except:
print(f"Invalid DELETE command syntax in '{commands}'")
elif command == "COUNT":
try:
if "WHERE" in parts[2]:
tableName, condPart = parts[1], parts[2].split("WHERE", 1)[1].strip()
else:
tableName, condPart = parts[1], ""
count(database, tableName, condPart)
except:
print(f"Invalid COUNT command syntax in '{commands}'")
elif command == "JOIN":
try:
table1Name, table2Name = parts[1].split(",")
colName = parts[2].replace("ON", "").strip()
join(database, table1Name.strip(), table2Name.strip(), colName.strip())
except:
print(f"Invalid JOIN command syntax in '{command}'")
if __name__ == "__main__":
main()