-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.py
792 lines (694 loc) · 27.2 KB
/
handler.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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
from abc import ABC
import abc
import json
import logging
import sqlite3
import yaml
import tornado.web
from tornado import gen
from tornado.web import HTTPError
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import mysql.connector
from controller.rewriter import ControllerDatabase, ControllerRewriter, \
ControllerEncryptSql, ControllerDatabase_jar, ControllerEncryptSql1, ControllerEncryptSql2, ControllerDecrypt
NUMBER_OF_EXECUTOR = 100
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
with open("config.yaml", 'r', encoding='utf-8') as f:
cfg = f.read()
config = yaml.full_load(cfg)
if config['meta']['type'] == 'mysql':
db_conn = mysql.connector.connect(
host=config['meta']['mysql']["host"],
database=config['meta']['mysql']["db"],
user=config['meta']['mysql']["user"],
passwd=config['meta']['mysql']["passwd"],
port=int(config['meta']['mysql']["port"])
)
else:
db_conn = sqlite3.connect(config['meta']['sqlite'])
def test_connection(_db_conn):
try:
_db_conn.ping()
except:
_db_conn = mysql.connector.connect(
host=config['meta']['mysql']["host"],
database=config['meta']['mysql']["db"],
user=config['meta']['mysql']["user"],
passwd=config['meta']['mysql']["passwd"],
port=int(config['meta']['mysql']["port"])
)
return _db_conn
class BasePostRequestHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Max-Age', 1000)
self.set_header('Content-type', 'application/json')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Origin, '
'Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')
executor = ThreadPoolExecutor(NUMBER_OF_EXECUTOR)
@gen.coroutine
def post(self, *args, **kwargs):
try:
result = yield self._post(*args, **kwargs)
self.write(result)
except HTTPError as e:
self.write(e)
except Exception as e:
logger.error(e)
raise HTTPError(404, "No results")
@run_on_executor
def _post(self, *args, **kwargs):
request = self._post_request_arguments(*args, **kwargs)
res = self._request_service(**request)
return res
@abc.abstractmethod
def _post_request_arguments(self, *args, **kwargs):
raise NotImplementedError('call to abstract method %s._get_request_arguments' % self.__class__)
@abc.abstractmethod
def _request_service(self, **kwargs):
raise NotImplementedError('call to abstract method %s._request_service' % self.__class__)
class PostHandler(BasePostRequestHandler, ABC):
def _post_request_arguments(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
logger.info(self.__class__.__name__)
data = json.loads(self.request.body)
if not data:
raise HTTPError(400, "Query argument cannot be empty string")
return data
def _request_service(self, **kwargs):
"""
:param kwargs:
:return:
"""
if kwargs:
c_e = ControllerDatabase(kwargs)
res = c_e.do_query()
else:
raise HTTPError(400, "Query argument cannot be empty string")
return res
class PostHandler_jar(BasePostRequestHandler, ABC):
def _post_request_arguments(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
logger.info(self.__class__.__name__)
data = {}
if isinstance(self.request.arguments, dict):
for k, v in self.request.arguments.items():
data[k] = v[0].decode('UTF-8')
if not data:
raise HTTPError(400, "Query argument cannot be empty string")
return data
def _request_service(self, **kwargs):
"""
:param kwargs:
:return:
"""
if kwargs:
c_e = ControllerDatabase_jar(kwargs)
res = c_e.do_query()
else:
raise HTTPError(400, "Query argument cannot be empty string")
return res
class RewriteHandler(BasePostRequestHandler, ABC):
def _post_request_arguments(self, *args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
logger.info(self.__class__.__name__)
try:
data = json.loads(self.request.body)
except Exception as e:
data = self.request.arguments
if not data:
raise HTTPError(400, "Query argument cannot be empty string")
return data
def _request_service(self, **kwargs):
"""
:param kwargs:
:return:
"""
if kwargs:
c_e = ControllerRewriter(kwargs)
res = c_e.do_rewrite()
else:
raise HTTPError(400, "Query argument cannot be empty string")
return res
class QueryHandler(tornado.web.RequestHandler, ABC):
executor = ThreadPoolExecutor(NUMBER_OF_EXECUTOR)
ENCRYPT_KEY = "1234salt1234salt"
ENCRYPT_IV = "5678salt5678salt"
def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Max-Age', 1000)
self.set_header('Content-type', 'application/json')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Origin, '
'Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')
def options(self):
self.set_status(204)
self.finish()
@run_on_executor
def _post(self, *args, **kwargs):
query_para = json.loads(self.request.body)
encrypted_columns = {}
ciphertext = True
if "create_table" in query_para.keys():
query = query_para['create_table']
data_source_id = query_para['selectedJdbcDataSource']['value']
encrypted_columns = query_para['encrypted_columns']
else:
query = query_para['sqlQuery']
while query[-1] == ";":
query = query[:-1]
data_source_id = query_para["jdbcDataSourceId"]
ciphertext = query_para['ciphertext']
query = query
cx = test_connection(db_conn)
cu = cx.cursor()
cu.execute("SELECT id, name, connection_url, driver_class_name, "
"username, password, ping FROM p_datasource WHERE id={}".format(data_source_id))
db_info = cu.fetchall()
cx.commit()
cu.close()
jdbc = db_info[0][2]
if jdbc[:13] == "jdbc:mysql://":
host_port = jdbc[13:].split("/")[0]
host = host_port.split(":")[0]
port = host_port.split(":")[1]
db = jdbc[13:].split("/")[1]
user = db_info[0][4]
password = db_info[0][5]
kwargs = {
'host': host,
'db': db,
'user': user,
'password': password,
'query': query,
'port': int(port),
'encrypted_columns': encrypted_columns,
'ciphertext': ciphertext
}
if 'resultLimit' in query_para.keys():
kwargs['limit'] = int(query_para['resultLimit'])
c_e = ControllerDatabase(kwargs)
if "create_table" not in query_para.keys():
res = c_e.do_query()
return self.format_result(res)
else:
c_e.do_create()
return {}
else:
return {}
@gen.coroutine
def post(self, *args, **kwargs):
try:
result = yield self._post(*args, **kwargs)
self.write(result)
except HTTPError as e:
self.write(e)
except Exception as e:
self.write({'error': str(e)})
logger.error(e)
raise HTTPError(404, "No results")
@staticmethod
def format_result(res):
if not res['result']:
return {}
columns = res['columns']
format_res = {'columns': [],
"data": [],
"error": None}
order_columns = []
for k, v in zip(*columns):
format_res['columns'].append(build_columns(k, v))
order_columns.append(k)
result = res["result"]
data = []
if result:
if len(result[0]) > len(order_columns):
order_columns = ["null" + str(i) for i in range(len(result[0]))]
format_res['columns'] = []
for k, v in zip(order_columns, result[0]):
tmp = build_columns(k, 'int') if isinstance(v, int) else build_columns(k, 'varchar')
format_res['columns'].append(tmp)
for row in result:
format_row = {}
for k, v in zip(order_columns, row):
format_row[k] = v
data.append(json.dumps(format_row))
format_res["data"] = "[" + ",".join(data) + "]"
return format_res
class EncryptSqlHandler(tornado.web.RequestHandler, ABC):
executor = ThreadPoolExecutor(NUMBER_OF_EXECUTOR)
ENCRYPT_KEY = "1234salt1234salt"
ENCRYPT_IV = "5678salt5678salt"
def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Max-Age', 1000)
self.set_header('Content-type', 'application/json')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Origin, '
'Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')
def options(self):
self.set_status(204)
self.finish()
@run_on_executor
def _post(self, *args, **kwargs):
query_para = json.loads(self.request.body)
if 'backend' in query_para.keys():
c_e = ControllerEncryptSql(query_para)
res = c_e.do_convert()
return res
query = query_para['sqlQuery']
while query[-1] == ";":
query = query[:-1]
data_source_id = query_para["jdbcDataSourceId"]
query = query
cx = test_connection(db_conn)
cu = cx.cursor()
cu.execute("SELECT id, name, connection_url, driver_class_name, "
"username, password, ping FROM p_datasource WHERE id={}".format(data_source_id))
db_info = cu.fetchall()
cx.commit()
cu.close()
jdbc = db_info[0][2]
if jdbc[:13] == "jdbc:mysql://":
host_port = jdbc[13:].split("/")[0]
host = host_port.split(":")[0]
port = host_port.split(":")[1]
db = jdbc[13:].split("/")[1]
user = db_info[0][4]
password = db_info[0][5]
kwargs = {
'host': host,
'db': db,
'user': user,
'password': password,
'query': query,
'port': int(port),
}
c_e = ControllerEncryptSql(kwargs)
res = c_e.do_convert()
return res
else:
return {'encrypt_sql': ''}
@gen.coroutine
def post(self, *args, **kwargs):
try:
result = yield self._post(*args, **kwargs)
self.write(result)
except HTTPError as e:
self.write(e)
except Exception as e:
self.write({'error': str(e)})
logger.error(e)
raise HTTPError(404, "No results")
class EncryptSqlHandler1(tornado.web.RequestHandler, ABC):
executor = ThreadPoolExecutor(NUMBER_OF_EXECUTOR)
ENCRYPT_KEY = "1234salt1234salt"
ENCRYPT_IV = "5678salt5678salt"
def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Max-Age', 1000)
self.set_header('Content-type', 'application/json')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Origin, '
'Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')
def options(self):
self.set_status(204)
self.finish()
@run_on_executor
def _post(self, *args, **kwargs):
para = json.loads(self.request.body)
kwargs = {
'db': para['db'],
'sql': para['sql'],
}
c_e = ControllerEncryptSql1(kwargs)
res = c_e.do_convert()
return res
@gen.coroutine
def post(self, *args, **kwargs):
try:
result = yield self._post(*args, **kwargs)
self.write(result)
except HTTPError as e:
self.write(e)
except Exception as e:
self.write({'error': str(e)})
logger.error(e)
raise HTTPError(404, "No results")
class EncryptSqlHandler2(tornado.web.RequestHandler, ABC):
executor = ThreadPoolExecutor(NUMBER_OF_EXECUTOR)
ENCRYPT_KEY = "1234salt1234salt"
ENCRYPT_IV = "5678salt5678salt"
def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Max-Age', 1000)
self.set_header('Content-type', 'application/json')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Origin, '
'Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')
def options(self):
self.set_status(204)
self.finish()
@run_on_executor
def _post(self, *args, **kwargs):
para = json.loads(self.request.body)
kwargs = {
'db': para['db'],
'sql': para['sql'],
}
c_e = ControllerEncryptSql2(kwargs)
res = c_e.do_convert()
return res
@gen.coroutine
def post(self, *args, **kwargs):
try:
result = yield self._post(*args, **kwargs)
self.write(result)
except HTTPError as e:
self.write(e)
except Exception as e:
self.write({'error': str(e)})
logger.error(e)
raise HTTPError(404, "No results")
class DecryptResult(tornado.web.RequestHandler, ABC):
executor = ThreadPoolExecutor(NUMBER_OF_EXECUTOR)
ENCRYPT_KEY = "1234salt1234salt"
ENCRYPT_IV = "5678salt5678salt"
def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Max-Age', 1000)
self.set_header('Content-type', 'application/json')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Origin, '
'Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')
def options(self):
self.set_status(204)
self.finish()
@run_on_executor
def _post(self, *args, **kwargs):
"""
columns:col1,col2,col3,col4, rows:r1c1,r1c2,r1c3,r1c4;r2c1,r2c2,r2c3,r2c4
"""
para = json.loads(self.request.body)
# print(f"req data:{para}")
kwargs = {
'query_id': para['query_id'],
'data': para['data'],
}
c_e = ControllerDecrypt(kwargs)
res = c_e.do_convert()
return res
@gen.coroutine
def post(self, *args, **kwargs):
try:
result = yield self._post(*args, **kwargs)
self.write(result)
except HTTPError as e:
self.write(e)
except Exception as e:
self.write({'error': str(e)})
logger.error(e)
raise HTTPError(404, "No results")
class CreateHandler(tornado.web.RequestHandler, ABC):
executor = ThreadPoolExecutor(NUMBER_OF_EXECUTOR)
ENCRYPT_KEY = "1234salt1234salt"
ENCRYPT_IV = "5678salt5678salt"
def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Max-Age', 1000)
self.set_header('Content-type', 'application/json')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Origin, '
'Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')
def options(self):
self.set_status(204)
self.finish()
self.write('{"errorCode":"00","errorMessage","success"}')
@run_on_executor
def _post(self, *args, **kwargs):
query_para = json.loads(self.request.body)
data_source_id = query_para['selectedJdbcDataSource']['value']
query, encrypted_columns = self.generate_table(query_para['dataSource'], query_para['count'],
query_para['table_name'])
cx = test_connection(db_conn)
cu = cx.cursor()
cu.execute("SELECT id, name, connection_url, driver_class_name, "
"username, password, ping FROM p_datasource WHERE id={}".format(data_source_id))
db_info = cu.fetchall()
cx.commit()
cu.close()
jdbc = db_info[0][2]
if jdbc[:13] == "jdbc:mysql://":
host_port = jdbc[13:].split("/")[0]
host = host_port.split(":")[0]
port = host_port.split(":")[1]
db = jdbc[13:].split("/")[1]
user = db_info[0][4]
password = db_info[0][5]
kwargs = {
'host': host,
'db': db,
'user': user,
'password': password,
'query': query,
'port': int(port),
'encrypted_columns': encrypted_columns
}
if 'resultLimit' in query_para.keys():
kwargs['limit'] = int(query_para['resultLimit'])
c_e = ControllerDatabase(kwargs)
c_e.do_create()
return {}
else:
return {}
@gen.coroutine
def post(self, *args, **kwargs):
try:
result = yield self._post(*args, **kwargs)
self.write(result)
except HTTPError as e:
self.write(e)
except Exception as e:
logger.error(e)
raise HTTPError(404, "No results")
@staticmethod
def generate_table(columns, size, table_name):
query = "create table if not exists {}".format(table_name)
encrypted_columns = {}
part = []
for i in range(size):
col = columns[i]
if int(col['length']) > 0 and col['type'].lower() not in ['int']:
part.append(col['name'] + " " + col['type'] + "(" + col['length'] + ")")
else:
part.append(col['name'] + " " + col['type'])
if col['encryption'].lower() == 'true':
if col['fuzzy'].lower() == 'true':
encrypted_columns[col['name']] = {
"fuzzy": True,
"key": col['token']
}
else:
encrypted_columns[col['name']] = {
"fuzzy": False,
"key": col['token']
}
part = ", ".join(part)
query = query + "(" + part + ")"
return query, encrypted_columns
def build_columns(k, v):
if v == 'varchar':
return {"name": k,
"javaType": "VARCHAR",
"dbType": "VARCHAR",
"length": 100
}
else:
return {"name": k,
"javaType": "INTEGER",
"dbType": "INT",
"length": 10
}
class QueryComponentHandler(tornado.web.RequestHandler, ABC):
executor = ThreadPoolExecutor(NUMBER_OF_EXECUTOR)
ENCRYPT_KEY = "1234salt1234salt"
ENCRYPT_IV = "5678salt5678salt"
def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Max-Age', 1000)
self.set_header('Content-type', 'application/json')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Origin, '
'Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')
def options(self, component_id=None):
self.set_status(204)
self.finish()
self.write('{"errorCode":"00","errorMessage","success"}')
@run_on_executor
def _post(self, component_id=None):
query_para = json.loads(self.request.body)
cx = test_connection(db_conn)
cu = cx.cursor()
cu.execute("SELECT id, name, connection_url, driver_class_name, "
"username, password, ping FROM p_datasource WHERE id={}".format(component_id))
db_info = cu.fetchall()
cx.commit()
cu.close()
jdbc = db_info[0][2]
if jdbc[:13] == "jdbc:mysql://":
host_port = jdbc[13:].split("/")[0]
host = host_port.split(":")[0]
port = host_port.split(":")[1]
db = jdbc[13:].split("/")[1]
user = db_info[0][4]
password = db_info[0][5]
kwargs = {
'host': host,
'db': db,
'user': user,
'password': password,
'port': int(port),
}
c_e = ControllerDatabase(kwargs)
if "create_table" not in query_para.keys():
res = c_e.do_query()
return self.format_result(res)
else:
c_e.do_create()
else:
return {}
@gen.coroutine
def post(self, component_id=None):
try:
result = yield self._post(component_id)
self.write(result)
except HTTPError as e:
self.write(e)
except Exception as e:
logger.error(e)
raise HTTPError(404, "No results")
@staticmethod
def format_result(res):
if not res['result']:
return {}
columns = res['columns']
format_res = {'columns': [],
"data": [],
"error": None}
order_columns = []
for k, v in columns.items():
if v == 'varchar':
format_res['columns'].append({"name": k,
"javaType": "VARCHAR",
"dbType": "VARCHAR",
"length": 100
})
elif v == 'int':
format_res['columns'].append({"name": k,
"javaType": "INTEGER",
"dbType": "INT",
"length": 10
})
order_columns.append(k)
result = res["result"]
data = []
for row in result:
format_row = {}
for k, v in zip(order_columns, row):
format_row[k] = v
data.append(json.dumps(format_row))
format_res["data"] = "[" + ",".join(data) + "]"
return format_res
class SchemaHandler(tornado.web.RequestHandler, ABC):
executor = ThreadPoolExecutor(NUMBER_OF_EXECUTOR)
def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Max-Age', 1000)
self.set_header('Content-type', 'application/json')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Origin, '
'Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')
@run_on_executor
def get(self, component_id=None):
cx = test_connection(db_conn)
cu = cx.cursor()
cu.execute("SELECT id, name, connection_url, driver_class_name, "
"username, password, ping FROM p_datasource WHERE id={}".format(component_id))
db_info = cu.fetchall()
connection_url = db_info[0][2]
if connection_url[:13] == "jdbc:mysql://":
db = connection_url[13:]
cu.execute(
"SELECT table_name, col_info FROM p_db_meta WHERE database_name='{}' order by table_name".format(db))
self.write(self.format_result(cu.fetchall()))
else:
self.write({})
cx.commit()
cu.close()
@staticmethod
def format_result(tables_info):
res = []
table = {}
for row in tables_info:
format_col = {}
if not table:
table["name"] = row[0]
table["type"] = "USER TABLE"
table["columns"] = []
col = json.loads(row[1])
for key, value in col.items():
if value['type'] == 'varchar':
format_col = {
"name": key if value['plaintext'] else key + " *",
"javaType": "VARCHAR",
"dbType": "VARCHAR",
"length": 258
}
elif value['type'] == 'int':
format_col = {
"name": key if value['plaintext'] else key + " *",
"javaType": "INTEGER",
"dbType": "INT UNSIGNED",
"length": 20
}
if row[0] == table["name"]:
table["columns"].append(format_col)
else:
res.append(json.dumps(table))
table = {"name": row[0], "type": "USER TABLE", "columns": []}
table["columns"].append(format_col)
res.append(json.dumps(table))
return "[" + ",".join(res) + "]"