forked from ambujraj/AmbSQL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAmbSQL.py
executable file
·421 lines (419 loc) · 20.6 KB
/
AmbSQL.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
#!usr/bin/env python3
import sys
import getpass
import string
import sqlite3
import os
import datetime
if(os.name=='nt'):
os.system("title "+"AmbSQL")
try:
os.system("IF NOT EXIST C:\AmbSQL MKDIR C:\AmbSQL") # Create Folder AmbSQL for storage of Database file
except:
pass
path = 'C:\\AmbSQL\\'
# For Linux and MacOS
else:
try:
os.system("mkdir -p /home/"+os.getlogin()+"/DB")
except:
pass
path = '/home/'+os.getlogin()+'/DB/'
db = sqlite3.connect(path+"dtables.db") # Connect to Tables Database
c = db.cursor()
dbu = sqlite3.connect(path+"duser.db") # Connect to Users Database
cu = dbu.cursor()
cu.execute("CREATE TABLE IF NOT EXISTS USERS(id INTEGER PRIMARY KEY,user TEXT,pass TEXT)")
dbu.commit()
usern = ""
def main(cnt):
if(os.name == 'nt'):
os.system("cls")
else:
os.system("clear")
print("AmbSQL shell version: 1.0.2 "+str(datetime.datetime.now()))
print("")
print("Type 'docs()' for documentation")
print("")
while(True):
try:
command = input("> ").lower().strip() # Input Command
if(command == "connect"):
cnt = 0
usern = str(input("Enter user-name: ")).lower().strip() # Input Username
passw = str(getpass.getpass('Enter password: ')) # Input Password
# Username, Password Auth
if(usern == "system" and passw == "123"):
cnt = 1
print("Connected.")
else:
temp = cu.execute("SELECT USER,PASS FROM USERS WHERE USER= ? AND PASS= ?", (usern, passw))
for i in temp:
if(str(i[0]) == str(usern) and str(i[1]) == str(passw)):
cnt = 1
print("Connected.")
break
if(cnt == 0):
print("Username or Password entered wrong!!")
del usern
del temp
# Create Table
elif(command.startswith("createtable(") and command.endswith(")")):
if (cnt != 1):
print("ERROR: Not Connected !!")
else:
abc = command[12:-1].upper()
if (len(abc) != 0):
l1 = abc.split(",")
if (len(l1) >= 2):
tname = l1[0]
a = []
for i in range(1, len(l1)):
a.insert(i - 1, l1[i].lower().strip())
try:
c.execute("CREATE TABLE " + tname +" (id INTEGER PRIMARY KEY,last_mod TEXT)")
for j in range(1, len(l1)):
c.execute("ALTER TABLE " + tname +" ADD " + a[j - 1] + " TEXT")
db.commit()
print("Table Created.")
except:
print("ERROR!! Table Name and Attribute name should be unique!")
del tname, a
else:
print("ERROR!! There should be atleast two Parameters!")
del l1
else:
print("ERROR!! Please Enter the Table name!")
del abc
# Insert Values into Table
elif(command.startswith("insertvalues(") and command.endswith(")")):
if(cnt != 1):
print("ERROR: Not Connected !!")
else:
abc = command[13:-1].upper().strip()
if(len(abc) != 0):
l1 = abc.split(",")
if(len(l1) >= 2):
tname = str(l1[0])
a = []
for i in range(1, len(l1)):
a.insert(i-1, str(l1[i]).lower().strip())
at = tuple(a)
try:
c.execute("INSERT INTO "+tname +" VALUES(NULL,?"+",?"*(len(l1)-1)+")", (usern,)+at)
db.commit()
print("One row inserted.")
except:
print("ERROR!! Invalid Entry!")
del at, a, tname
else:
print("ERROR!! There should be atleast two Parameters!")
del l1
else:
print("ERROR!! Please Enter the Table name!")
del abc
# Create New User
elif(command.startswith("createuser(") and command.endswith(")")):
if(cnt != 1):
print("ERROR: Not Authorized !!")
elif(usern == "system"):
abc = command[11:-1].lower().strip()
if(len(abc) != 0):
l1 = abc.split(",")
if(len(l1) == 2):
l1[0] = l1[0].strip()
l1[1] = l1[1].strip()
at = tuple(l1)
try:
cu.execute("INSERT INTO USERS VALUES(NULL,?,?)", at)
dbu.commit()
print("User Created.")
except:
print("ERROR!! Invalid Entry!")
del at
else:
print("ERROR!! There should be two Parameters!")
del l1
else:
print("ERROR!! Please Enter the Table name!")
del abc
else:
print("ERROR: Not Authorized !!")
# Delete Existing User
elif(command.startswith("deleteuser(") and command.endswith(")")):
if(cnt != 1):
print("ERROR: Not Authorized !!")
elif(usern == "system"):
abc = command[11:-1].lower().strip()
if(len(abc) != 0):
l1 = abc.split(",")
if(len(l1) == 1):
l1[0] = l1[0].strip()
at = tuple(l1)
try:
cu.execute("DELETE FROM USERS WHERE user= ?", at)
dbu.commit()
print("User Deleted.")
except:
print("ERROR!! Invalid Entry!")
del at
else:
print("ERROR!! There should be one Parameters!")
del l1
else:
print("ERROR!! Please Enter the Table name!")
del abc
else:
print("ERROR: Not Authorized !!")
# Show Schema
elif(command.startswith("showtable(") and command.endswith(")")):
if(cnt != 1):
print("ERROR: Not Connected !!")
else:
abc = command[10:-1].upper().strip()
if(len(abc) != 0):
try:
c.execute("pragma table_info('"+abc+"')")
abv = c.fetchall()
print(" cid\t name\t pk")
print("----------\t--------\t---------")
for p, q, r, s, t, u in abv:
print(" "*(10-len(str(p)))+str(p)+"\t"+" " *(8-len(str(q)))+str(q)+"\t"+" "*(9-len(str(u)))+str(u))
print("")
except:
print("ERROR!! Table Not Found!")
else:
print("ERROR!! Please Enter the Table name!")
# Show Values In Table
elif(command.startswith("showvalues(") and command.endswith(")")):
if(cnt != 1):
print("ERROR: Not Connected !!")
else:
try:
abc = command[11:-1].upper().strip()
if(len(abc) != 0):
c.execute("pragma table_info('"+abc+"')")
abv = c.fetchall()
for p, q, r, s, t, u in abv:
print(" "*(9-len(str(q)))+str(q), end="\t")
print("")
for p, q, r, s, t, u in abv:
print("---------", end="\t")
print("")
c.execute("SELECT * FROM "+abc)
tables = c.fetchall()
for i in tables:
for j in i:
print(" "*(9-len(str(j)))+str(j), end="\t")
print("")
'''
c.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = c.fetchall()
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
table.to_csv(path+table_name +'.csv', index=None)
pdr = pd.read_csv(path+abc+'.csv')
print(pdr)
del pdr
'''
else:
print("ERROR!! Please Enter the Table name!")
del abc
except:
print("ERROR!! Table Not Found!")
# Delete Rows Either with Condition or Truncate Table
elif(command.startswith("deletetable(") and command.endswith(")")):
if (cnt != 1):
print("ERROR: Not Connected !!")
else:
abc = command[12:-1]
if (len(abc) != 0):
l1 = abc.split(",")
if(len(l1) == 1):
tname = l1[0].strip().upper()
try:
c.execute("DELETE FROM "+tname)
db.commit()
#os.system("IF EXIST C:\AmbSQL\\" + tname +".csv " + "DEL /F C:\AmbSQL\\" + tname + ".csv")
print("All Rows Deleted.")
except:
print("ERROR!! Invalid Table name!")
del tname
elif(len(l1) == 2):
tname = l1[0].strip().upper()
drow = l1[1].lower()
dd = drow.split("==")
if(len(dd) == 2):
col = dd[0].strip()
if(col=='id'):
valued = dd[1].strip()
else:
valued = str(dd[1]).strip()
try:
if(col=='id'):
c.execute("DELETE FROM "+tname +" WHERE "+col+"="+valued+";")
else:
c.execute("DELETE FROM "+tname + " WHERE "+col+" = '"+valued+"';")
db.commit()
#os.system("IF EXIST C:\AmbSQL\\" + tname + ".csv " + "DEL /F C:\AmbSQL\\" + tname + ".csv")
print("Row(s) Deleted.")
except:
print("ERROR!! Invalid Parameters!")
del col, valued
else:
print("ERROR!! Invalid Equivalence of Row and Value!")
del dd, drow, tname
else:
print("ERROR!! Entry should contain one or two parameters!")
del l1
else:
print("ERROR!! Entry should have atleast one parameter!")
del abc
# Update Values in Table either with condition or with no condition
elif(command.startswith("updatevalue(") and command.endswith(")")):
if (cnt != 1):
print("ERROR: Not Connected !!")
else:
abc = command[12:-1]
if(len(abc) != 0):
l1 = abc.split(",")
if(len(l1) == 2):
tname = l1[0].strip()
dd = l1[1].split("=")
if(len(dd)==2):
col = dd[0].strip()
valued = str(dd[1]).strip()
try:
c.execute("UPDATE "+tname+" SET "+col+"='"+valued+"';")
db.commit()
print("Row(s) Updated.")
except:
print("ERROR!! Invalid Parameters!")
del col, valued
else:
print("ERROR!! Invalid Entry!")
elif(len(l1)==3):
tname = l1[0].strip()
dd = l1[1].split("=")
if(len(dd) == 2):
col = dd[0].strip()
valued = str(dd[1]).strip()
dd1 = l1[2].split("==")
if(len(dd1)==2):
col1 = dd1[0].strip()
if(col1=='id'):
valued1 = dd1[1].strip()
else:
valued1 = str(dd1[1]).strip()
try:
if(col1=='id'):
c.execute("UPDATE "+tname+" SET "+col+"='"+valued+"' WHERE id= ?", (valued1))
else:
c.execute("UPDATE "+tname+" SET "+col+"='"+valued+"' WHERE "+col1+"='"+valued1+"';")
db.commit()
print("Row Updated.")
except:
print("ERROR!! Invalid Parameters!")
del col1, valued1
else:
print("ERROR!! Invalid Equivalence of Row and Value!")
del col, valued, dd1
else:
print("ERROR!! Invalid Entry!")
del tname, dd
else:
print("ERROR!! Entry should contain two or three parameters!")
del l1
else:
print("ERROR!! Entry should have atleast two parameter!")
del abc
# Clear the Screen
elif(command == "clear()"):
if(cnt != 1):
print("ERROR: Not Connected !!")
else:
main(1)
# Documentation
elif(command == "docs()"):
print("")
print("Copyright (c) 2018, Ambuj. All rights reserved.")
print("")
print("\tconnect - To login to Database")
print("\tcreatetable(<table-name>, <column1-name> , <column2-name>, ....) - To create new Table")
print("\tinsertvalues(<table_name>, <column1-value> , <column2-value>, ...) - To enter the values in Table")
print("\tshowtable(<table_name>) - To show the Table schema")
print("\tshowvalues(<table_name>) - To show the Table values")
print("\tupdatevalue(<table_name> , <assignment>) - To Update all values of column")
print("\tupdatevalue(<table_name> , <assignment> , <condition>) - To Update the values of column")
print("\tdeletetable(<table_name>) - To truncate the Table")
print("\tdeletetable(<table_name> , <condition>)(e.g- deletetable(ab,name==jack))- To delete row(s) from Table")
print("\tdroptable(<table_name>) - To drop the Table")
print("\taltertable(<old-table_name> , <new-table_name>) - To rename Table Name")
print("\tcreateuser(<user_name> , <password>) - To create new User")
print("\tdeleteuser(<user_name>) - To delete a User")
print("\tlogout() - To Logout")
print("\tclear() - To clear the Screen")
print("")
print("\tnote=> Username: 'system', password: '123'")
# Alter Table Name
elif(command.startswith("altertable(") and command.endswith(")")):
if(cnt != 1):
print("ERROR: Not Connected !!")
else:
abc = command[11:-1].upper()
try:
if(len(abc) != 0):
l1 = abc.split(",")
if(len(l1) == 2):
old1 = l1[0].strip()
new1 = l1[1].strip()
c.execute("ALTER TABLE "+old1 +" RENAME TO "+new1)
db.commit()
#os.system("IF EXIST C:\AmbSQL\\"+old1 +".csv "+"DEL /F C:\AmbSQL\\"+old1+".csv")
print("Table name Updated from " +
old1+" to "+new1)
del old1, new1
else:
print("ERROR!! There should be two Parameters!")
else:
print("ERROR!! Please Enter the Table names!")
except:
print("ERROR!! Invalid Table Name!")
del abc
# Drop Table
elif(command.startswith("droptable(") and command.endswith(")")):
if (cnt != 1):
print("ERROR: Not Connected !!")
else:
abc = command[10:-1].upper().strip()
if(len(abc) != 0):
try:
c.execute("DROP TABLE "+abc)
db.commit()
#os.system("IF EXIST C:\AmbSQL\\" + abc +".csv " + "DEL /F C:\AmbSQL\\" + abc + ".csv")
print("Table Dropped.")
except:
print("ERROR!! Invalid Table Name!")
else:
print("ERROR!! Please Enter the Table name!")
del abc
# Logout From Current Session
elif(command == "logout()"):
cnt = 0
print("Successfully Logged Out.")
else:
print("Command not found!!(please ensure you include '()' at the end)")
# Handle KeyBoard Interrupt
except KeyboardInterrupt:
print("KEYBOARD INTERRUPT")
dbu.close()
db.close()
if(os.name=='nt'):
os.system("cls")
else:
os.system("clear")
sys.exit(0)
# Call the main function
if __name__ == '__main__':
main(0)