-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConsoleSQL.py
550 lines (361 loc) · 16.8 KB
/
ConsoleSQL.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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import os
import shutil
from colorama import Fore
from documentation import documentation
import errors
def create_database(database, *args):
'''
Console command
CREATE DATABASE DataBaseName
'''
try:
os.mkdir(f"databases/{database}"), os.mkdir(f"databases/{database}/files"), os.mkdir(f"databases/{database}/tables"), os.mkdir(f"databases/{database}/queues")
except FileExistsError:
return Fore.LIGHTWHITE_EX + "Database already exists"
return Fore.LIGHTWHITE_EX + f"Database \"{database}\" was created"
def use_database(database, *args):
'''
Console command
USE DATABASE DataBaseName
'''
if os.path.exists(f"databases/{database}/"):
return [Fore.LIGHTWHITE_EX + f"Currently working with database \"{database}\"", database]
raise errors.DataBaseNotFoundError(f"Database \"{database}\" not found!")
def create_table(database, table, values, *args):
'''
Console command
CREATE TABLE TableName(id: int, name: str, age: float, more...)
'''
if os.path.exists(f"databases/{database}/tables/{table}.txt"):
return Fore.LIGHTWHITE_EX + f"Table already exists!"
table = open(f"databases/{database}/tables/{table}.txt", "a+")
table.write(f"{values}\n\n")
table.close()
return Fore.LIGHTWHITE_EX + f"Table \"{table.name.split('/')[-1][:-4]}\" was created!"
def add_content_to_table(database, table, *content):
'''
Console command
ADD TableName VALUES (
(id, name, age, more...)
(id, name, age)
);
'''
try:
with open(f"databases/{database}/tables/{table}.txt", "r") as file:
values = [line for line in file][0]
values_dictionary = {}
for item in values[1:-2].split(", "):
key, value = item.split(": ")
values_dictionary[key] = value
with open(f"databases/{database}/tables/{table}.txt", "a+") as write_file:
for content_list in content:
content_dict = {}
for index, item in enumerate(values_dictionary.keys()):
content_dict[item] = content_list[index]
if type(content_dict[item]) is int and values_dictionary[item] == "'int'" or \
type(content_dict[item]) is str and values_dictionary[item] == "'str'" or \
type(content_dict[item]) is float and values_dictionary[item] == "'float'":
continue
raise errors.ItemValueDifferentThanTheSetValue(f"item \"{item}\" is type \'{type(content_dict[item])}\' and it must be \'{values_dictionary[item]}\'")
write_file.write(f"{content_dict}\n")
except Exception as e:
raise e
return Fore.LIGHTWHITE_EX + "Content added to table!"
def create_file(database, file_name):
'''
Console command
CREATE FILE FileName
'''
if os.path.exists(f"databases/{database}/files/{file_name}.txt"):
return Fore.LIGHTWHITE_EX + "File already exists"
file = open(f"databases/{database}/files/{file_name}.txt", 'x')
file.close()
return Fore.LIGHTWHITE_EX + f"File \"{file_name}\" was created!"
def write_in_file(database, file, *content):
'''
Console command
WRITE IN FileName:
Something isn't right.
Some Messages!
content, content, content,
content, content,
content,
content,
content
;;;
'''
if os.path.exists(f"databases/{database}/files/{file}.txt"):
with open(f"databases/{database}/files/{file}.txt", "a+") as f:
for line in content:
f.write(f"{line}\n")
return Fore.LIGHTWHITE_EX + "Content added to file!"
return Fore.LIGHTWHITE_EX + f"Database \"{database}\" or File \"{file}\" not found!"
def create_queue(database, queue_file_name, *args):
'''
Console command
CREATE QUEUE QueueName
or
CREATE QUE QueueName
or
CREATE Q QueueName
'''
if os.path.exists(f"databases/{database}/queues/{queue_file_name}.txt"):
return Fore.LIGHTWHITE_EX + "Queue already exists"
file = open(f"databases/{database}/queues/{queue_file_name}.txt", 'x')
file.close()
return Fore.LIGHTWHITE_EX + f"Queue \"{queue_file_name}\" was created!"
def add_to_queue(database, queue, *items):
'''
Console command
ADD TO QueueName firstItem secondItem thirdItem
'''
if os.path.exists(f"databases/{database}/queues/{queue}.txt"):
with open(f"databases/{database}/queues/{queue}.txt", "a+") as q:
for item in items:
q.write(f"{item}\n")
return Fore.LIGHTWHITE_EX + "Items added to queue!"
return Fore.LIGHTWHITE_EX + f"Database \"{database}\" or Queue \"{queue}\" not found!"
def remove_from_queue(database, queue, *args):
'''
Console command
REMOVE FROM QueueName
'''
if os.path.exists(f"databases/{database}/queues/{queue}.txt"):
q = [item for item in open(f"databases/{database}/queues/{queue}.txt", "r")][1:]
os.remove(f"databases/{database}/queues/{queue}.txt")
f = open(f"databases/{database}/queues/{queue}.txt", "a+")
for item in q:
f.write(f"{item}")
f.close()
return "First element from queue removed!"
return f"Queue \"{queue}\" not found!"
def check_table_content(database, table, *args):
'''
Console command
GET ALL TableName
'''
if os.path.exists(f"databases/{database}/tables/{table}.txt"):
file = open(f"databases/{database}/tables/{table}.txt", "r")
return [Fore.LIGHTWHITE_EX + line for line in file][2:]
print(Fore.LIGHTWHITE_EX + "Table not found!")
return []
def check_file_content(database, file_name, *border):
'''
Console command
GET FILE FileName
'''
if os.path.exists(f"databases/{database}/files/{file_name}.txt"):
file = open(f"databases/{database}/files/{file_name}.txt", "r")
return [Fore.LIGHTWHITE_EX + line for line in file]
print(Fore.LIGHTWHITE_EX + "File not found!")
return []
def check_queue_content(database, queue, *args):
'''
Console command
GET QueueName
'''
if os.path.exists(f"databases/{database}/queues/{queue}.txt"):
q = [line for line in open(f"databases/{database}/queues/{queue}.txt", "r")]
return ', '.join(q)
return f"Queue {queue} not found!"
def delete_lines(database, path, file_name, *lines):
'''
Console command
DEL TABLE/FILE FileName LINES firstline secondline seventhline
'''
if path == "table":
if os.path.exists(f"databases/{database}/tables/{file_name}.txt"):
file = [line[:-1] if line[-1] == '\n' else line for line in open(f"databases/{database}/tables/{file_name}.txt", "r")]
for num, line in enumerate(lines):
if 0 <= (line+1)-num < len(file):
file.pop((line+1)-num)
os.remove(f"databases/{database}/tables/{file_name}.txt")
f = open(f"databases/{database}/tables/{file_name}.txt", "a+")
for line in file:
f.write(f"{line}\n")
f.close()
elif path == "file":
if os.path.exists(f"databases/{database}/files/{file_name}.txt"):
file = [line[:-1] if line[-1] == '\n' else line for line in open(f"databases/{database}/files/{file_name}.txt", "r")]
for num, line in enumerate(lines):
if 0 <= (line - 1) - num < len(file):
file.pop((line - 1) - num)
os.remove(f"databases/{database}/files/{file_name}.txt")
f = open(f"databases/{database}/files/{file_name}.txt", "a+")
for line in file:
f.write(f"{line}\n")
f.close()
else:
return Fore.LIGHTWHITE_EX + f"Invalid path name '{path}'"
return Fore.LIGHTWHITE_EX + "lines removed!"
def drop_database(*databases):
'''
Console command
One DataBase:
FIRST WAY: DROP DB DataBaseName
SECOND WAY: DROP DATABASE DataBaseName
More Than One DataBases:
FIRST WAY: DROP DBS FirstDataBaseName SecondDataBaseName ThirdDataBaseName...
SECOND WAY: DROP DATABASES FirstDataBaseName SecondDataBaseName ThirdDataBaseName...
'''
for db in databases:
if os.path.exists(f"databases/{db}/"):
shutil.rmtree(f"databases/{db}/")
return Fore.LIGHTWHITE_EX + "Database/s dropped!"
def drop_table(database, *tables):
'''
Console command
One Table:
DROP TABLE TableName
More Than One Table:
DROP TABLES FirstTableName SecondTableName ThirdTableName...
'''
for table in tables:
if os.path.exists(f"databases/{database}/tables/{table}.txt"):
os.remove(f"databases/{database}/tables/{table}.txt")
return Fore.LIGHTWHITE_EX + "Table/s dropped!"
def delete_file(database, *files):
'''
Console command
One File:
DEL FILE FileName
More Than One File:
DEL FILES FirstFileName SecondFileName ThirdFileName...
'''
for file in files:
if os.path.exists(f"databases/{database}/files/{file}.txt"):
os.remove(f"databases/{database}/files/{file}.txt")
return Fore.LIGHTWHITE_EX + "File/s deleted!"
def delete_queue(database, *queues):
'''
Console command
One Queue:
DEL QUEUE QueueName
More Than One Queue:
DEL QUEUES FirstQueueName SecondQueueName ThirdQueueName...
'''
for queue in queues:
if os.path.exists(f"databases/{database}/queues/{queue}.txt"):
os.remove(f"databases/{database}/queues/{queue}.txt")
return Fore.LIGHTWHITE_EX + "Queue/s deleted!"
def code_saver(user_input, code_file, new_line):
'''
Saves the code in the code file.
'''
file = open(f"src/{code_file}", "a+")
file.write(f"{user_input}{new_line}")
file.close()
def run_program():
see_documentation = input(Fore.LIGHTWHITE_EX + "Wanna see the documentation? 'yes' or 'no': ")
if see_documentation.lower() == "yes":
print(documentation())
while True:
db = input(Fore.LIGHTWHITE_EX + "create or use database: ")
if db == 'create':
create_db = input(Fore.LIGHTWHITE_EX + "database name: ")
create_database(create_db)
d = use_database(create_db)
break
elif db == "use":
d = use_database(input(Fore.LIGHTWHITE_EX + "database name: "))[-1]
break
database = d
while True:
file = input(Fore.LIGHTWHITE_EX + "Create or choose file where to save the code from your console experience:\n")
if not os.path.exists(f"src/{file}.txt"):
f = open(f"src/{file}.txt", "x")
f.close()
if file:
break
file = f"{file}.txt"
while True:
operation_code = input()
if operation_code == "END":
break
if operation_code == "docs":
print(documentation())
continue
operation = operation_code.lower().split()
code_saver(operation_code, file, '\n')
if len(operation) >= 2:
if operation[-1]:
if operation[:-1] == ["create", "database"]:
print(create_database(operation[-1]))
elif operation[:-1] == ["use", "database"]:
db = use_database(operation[-1])
print(db[0])
database = db[-1]
elif operation[:2] == ["create", "table"]:
table_name = ' '.join(operation[2:])[:' '.join(operation[2:]).index("(")]
values = ' '.join(operation[2:])[' '.join(operation[2:]).index("(")+1:' '.join(operation[2:]).index(")")]
values_tuple = values.split(", ")
values_dict = {}
for items in values_tuple:
key, value = items.split(": ")
values_dict[key] = value
print(create_table(database, table_name, values_dict))
elif operation[0] == "add" and operation[-2] == "values":
table = operation[1]
if operation[-1] == "(":
lst_values = []
item = input()
while item != ");":
code_saver(item, file, '\n')
items = item[1:-1].split(", ")
for index in range(len(items)):
if len(items[index].split(".")) == 2:
if items[index].split(".")[0].isdigit() and items[index].split(".")[1].isdigit():
items[index] = float(items[index])
elif items[index].isdigit():
items[index] = int(items[index])
lst_values.append(items)
item = input()
code_saver(item, file, '\n\n\n')
print(add_content_to_table(database, table, *lst_values))
elif operation[:-1] == ["create", "file"]:
print(create_file(database, operation[-1]))
elif operation[:-1] == ["write", "in"]:
content = []
text = input()
while text[-3:] != ";;;":
code_saver(text, file, '\n')
content.append(text)
text = input()
if operation[-1][-1] == ':':
print(write_in_file(database, operation[-1][:-1], *content))
else:
print(write_in_file(database, operation[-1], *content))
code_saver(text[-3:], file, '\n\n\n')
elif operation[0] == "create" and (operation[1] == "queue" or operation[1] == "que" or operation[1] == "q"):
print(create_queue(database, operation[-1]))
elif operation[0] == "add" and operation[1] == "to":
print(add_to_queue(database, operation[2], *operation[3:]))
elif operation[0] == "remove" and operation[1] == "from":
print(remove_from_queue(database, operation[-1]))
elif operation[0] == "get" and operation[1] == "all":
lines = check_table_content(database, operation[-1])
print()
[print(line) for line in lines]
elif operation[:-1] == ["get", "file"]:
lines = check_file_content(database, operation[-1])
print()
[print(line) for line in lines]
elif operation[0] == "get":
print(check_queue_content(database, operation[-1]))
elif len(operation) >= 5:
if operation[0] == "del" and operation[3] == "lines":
try:
print(delete_lines(database, operation[1], operation[2], *[int(l) for l in operation[4:]]))
except ValueError:
raise errors.InvalidLineError("line must be integer")
elif operation[:-1] == ["drop", "db"] or operation[:-1] == ["drop", "database"] or operation[:2] == \
["drop", "dbs"] or operation[:2] == ["drop", "databases"]:
dbs = operation[2:]
print(drop_database(*dbs))
elif operation[:2] == ["drop", "table"] or operation[:2] == ["drop", "tables"]:
print(drop_table(database, *operation[2:]))
elif operation[:2] == ["del", "file"] or operation[:2] == ["del", "files"]:
if "lines" not in operation:
print(delete_file(database, *operation[2:]))
elif operation[0] == "del" and operation[1] == "queue" or operation[1] == "queues":
print(delete_queue(database, *operation[2:]))