-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaterial.py
405 lines (289 loc) · 12.2 KB
/
material.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
from operator import eq
from xml.dom import minidom
import mysql.connector
import pymysql
from sqlalchemy import column, create_engine
import csv
import xml.etree.ElementTree as ET
import os
import pandas as pd
from collections import defaultdict
from tabulate import tabulate
import warnings
from sqlalchemy import exc as sa_exc
import pandasql
tree = ET.parse('./connecting.xml', parser = ET.XMLParser(encoding = 'iso-8859-5'))
def getDataSources(tree,datasource,name):
datasources={}
for node in tree.iter(datasource):
sourceDetails={}
for elem in node.iter():
if not elem.tag==node.tag:
if not next(elem.iter()):
sourceDetails[elem.tag]=elem.text
datasources[sourceDetails[name]]=sourceDetails
return (datasources)
rdbms=(getDataSources(tree,'rdbms_datasource','dbname'))
csvinfo=(getDataSources(tree,'csv_datasource','csvname'))
viewstore = (getDataSources(tree, 'viewstore', 'dbname'))
print(rdbms)
print(csvinfo)
print(viewstore)
#print(viewstore)
def parsing(sql):
sql=" ".join(sql.split())
# print (sql)
sql2=sql.lower()
start=0
database={}
all_as=[]
for i,n in enumerate(sql2.split()):
if n=="as":
# print(i)
all_as.append(i)
#s=sql2.split()
s=sql2.split()
for i in all_as[1:]:
database[s[i+1]]=s[i-1]
# print(database)
start=0
columns=defaultdict(list)
for _ in range(sql2.count("select")):
start=idx1=sql2.find("select",start)+6
start=idx2=sql2.find("from",start)
sub_str=sql[idx1:idx2].split(",")
# print ("sub_str",sub_str)
for i, substr in enumerate(sub_str):
if(substr.lower().startswith((" sum", " avg", " count", " max", " min"))):
sub_str[i] = substr[substr.find("(")+1:substr.find(")")]
# print("sub_str1",sub_str)
for i,n in enumerate(sub_str):
n=n.replace(" ","")
data_model,col=n.split(".")
columns[database[data_model]].append(col)
st = sql.split()
# print("st", st)
for i,n in enumerate(st):
if n=="==":
before=st[i-1].replace(" ","")
after=st[i+1].replace(" ","")
# print("hello")
# print(before)
# print(after)
data_model,col=before.split(".")
columns[database[data_model]].append(col)
data_model,col=after.split(".")
columns[database[data_model]].append(col)
# print(columns)
return columns
def generateDataFrames(columns, rdbms, csvinfo, sql):
df_list = {}
# print("in gendf", columns)
for i in columns:
columns[i]=list(set(columns[i]))
for key, value in columns.items():
if(key.startswith("sql")):
dbType, dbname, tablename = key.split("$")
mydb = mysql.connector.connect(
host=rdbms[dbname]["location"],
user=rdbms[dbname]["user-name"],
password=rdbms[dbname]["password"],
database=dbname
)
column = ",".join(value)
query = "SELECT {} FROM {}".format(column, tablename)
# print(query)
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=sa_exc.SAWarning)
# code here...
rdbms_pd = pd.read_sql(query, mydb)
key = key.replace("$", "_")
df_list[key] = rdbms_pd
# print(rdbms_pd)
elif(key.startswith("csv")):
dbType, dbname = key.split("$")
# print (csvinfo[dbname]['csv_loc'],value)
csv_pd = pd.read_csv(csvinfo[dbname]['csv_loc'], delimiter="\t", usecols=value)
key = key.replace("$", "_")
df_list[key] = csv_pd
# print(csv_pd)
uploadDataFrames(df_list,sql)
def uploadDataFrames(df_list, sql):
'''user = viewstore['views']["user-name"]
passw = viewstore['views']["password"]
host = viewstore['views']["location"] # either localhost or ip e.g. '172.17.0.2' or hostname address
port = 3306
database = 'views'
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=sa_exc.SAWarning)
viewsdb = create_engine('mysql+pymysql://' + user + ':' + passw + '@' + host + ':' + str(port) + '/' + database , echo=False)
for key, value in df_list.items():
# print(key)
# print(value)
# key = key.replace(".", "_")
# print(key)
value.to_sql(key, viewsdb)
joinDataFrames(sql, df_list.keys())'''
print("printing df_list", df_list)
view_definition_query = sql.replace("$", "_")
view_definition_query = view_definition_query.replace("==", "=")
view_definition_query = view_definition_query+";"
view_definition_query_list = view_definition_query.split(" ")
view_name = view_definition_query_list[2] + "_view"
print(view_name)
view_definition_query_to_run = " ".join(view_definition_query_list[4:])
sqlenv = lambda q: pandasql.sqldf(q, df_list)
req_df = sqlenv(view_definition_query_to_run)
#df_list["req_df"] = req_df
print(req_df)
user = viewstore['views']["user-name"]
passw = viewstore['views']["password"]
host = viewstore['views']["location"] # either localhost or ip e.g. '172.17.0.2' or hostname address
port = 3306
database = 'views'
print(user, passw, host)
viewsdb = create_engine('mysql+pymysql://' + user + ':' + passw + '@' + host + ':' + str(port) + '/' + database , echo=False)
req_df.to_sql(view_name, viewsdb)
def joinDataFrames(sql, df_list):
viewsdb = mysql.connector.connect(
host=viewstore['views']["location"],
user=viewstore['views']["user-name"],
password=viewstore['views']["password"],
database='views'
)
sql = sql.replace("==", "=")
cursor = viewsdb.cursor()
print(sql)
cursor.execute(sql)
viewname = sql.split()[2]
query = "CREATE TABLE {}_view AS (SELECT * FROM {})".format(viewname, viewname)
cursor.execute(query)
query = "DROP VIEW {}".format(viewname)
cursor.execute(query)
for key in df_list:
new_query = "DROP TABLE {}".format(key)
cursor.execute(new_query)
def getView(viewname):
viewsdb = mysql.connector.connect(
host=viewstore['views']["location"],
user=viewstore['views']["user-name"],
password=viewstore['views']["password"],
database='views'
)
query = "SELECT * FROM {}_view".format(viewname)
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=sa_exc.SAWarning)
# code here...
req_view = pd.read_sql(query, viewsdb)
return req_view
def QueryView(sql):
viewsdb = mysql.connector.connect(
host=viewstore['views']["location"],
user=viewstore['views']["user-name"],
password=viewstore['views']["password"],
database='views'
)
# cursor = viewsdb.cursor()
# cursor.execute(sql)
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=sa_exc.SAWarning)
# code here...
queried_db = pd.read_sql(sql, viewsdb)
# print(queried_db)
return queried_db
def listViewNames():
viewsdb = mysql.connector.connect(
host=viewstore['views']["location"],
user=viewstore['views']["user-name"],
password=viewstore['views']["password"],
database='views'
)
cursor = viewsdb.cursor()
query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.tables WHERE TABLE_NAME LIKE '%_view' AND table_schema = 'views'"
cursor.execute(query)
tables_list = []
for table in [tables[0] for tables in cursor.fetchall()]:
# print(table)
tables_list.append(table)
return tables_list
def dropView(viewname):
viewsdb = mysql.connector.connect(
host=viewstore['views']["location"],
user=viewstore['views']["user-name"],
password=viewstore['views']["password"],
database='views'
)
cursor = viewsdb.cursor()
viewname = viewname+"_view"
new_query = "DROP TABLE {}".format(viewname)
cursor.execute(new_query)
#-----------------------------------TESTBENCH FOR CHECKING THE MATERIAL VIEW GENERATION--------------------------
def app():
print("Select whether you wish to:")
print("1) Query an Existing View")
print("2) Create a New View")
option = int(input())
if(option == 2):
print("Enter your View Definition:")
sql = input()
viewname = sql.split()[2]
columns = parsing(sql=sql)
generateDataFrames(columns, rdbms, csvinfo, sql)
req_view = getView(viewname)
print(tabulate(req_view, headers='keys', tablefmt='psql'))
print("Type yes if you wish to query the view.")
isQuery = input().lower()
if(isQuery == "yes"):
print("In query mode, please enter break to exit.")
while(1):
print("Enter Query to Run or break to Exit")
query = input()
if(query.lower() == "break"):
break
else:
query = query.replace(viewname, viewname+"_view")
print(query)
queried_view = QueryView(query)
print(tabulate(queried_view, headers='keys', tablefmt='psql'))
print("-------Query Done-------")
else:
print("-------View has been stored-------")
print("-------View has been stored-------")
if(option == 1):
while(1):
print("Enter view name to be loaded or quit to exit")
viewname = input()
if(viewname == "quit"):
break
else:
viewlist = listViewNames()
viewnameexists = viewname+"_view"
if(viewnameexists in viewlist):
req_view = getView(viewname)
print(tabulate(req_view, headers='keys', tablefmt='psql'))
print("Type yes if you wish to query the view.")
isQuery = input().lower()
if(isQuery == "yes"):
print("In query mode, please enter break to exit.")
while(1):
print("Enter Query to Run or break to Exit")
query = input()
if(query.lower() == "break"):
break
else:
query = query.replace(viewname, viewname+"_view")
print(query)
queried_view = QueryView(query)
print(tabulate(queried_view, headers='keys', tablefmt='psql'))
print("-------Query Done-------")
else:
print("-------Will Be Taken Back to View Loading Menu-------")
# sql = input()
# columns = parsing(sql)
# generateDataFrames(columns, rdbms, csvinfo, sql)
# queried_pd = QueryView("SELECT cust_id,sum_sales from connect_view where sum_sales > 1000.0 order by sum_sales")
# tables_list = listViewNames()
# joinDataFrames(sql)
# CREATE View location2 AS SELECT p.empId, p.name, q.Role FROM sql_qwe_employee as p INNER JOIN csv_employee as q ON p.empId == q.empId
# CREATE VIEW demo as select dc.Cust_id, dc.product_category, sum(fs.Sales) as sum_sales from csv$star as fs inner join ( select pq.product_category, ls.cust_id from sql$marketdb$dim_prod as pq inner join sql$marketdb$fact_sales as ls on pq.prod_id == ls.prod_id ) as dc on dc.Cust_id == fs.Cust_id group by dc.Cust_id, dc.product_category;
# SELECT cust_id from demo where sum_sales > 5000