-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
oracle.py
1382 lines (1328 loc) · 63.7 KB
/
oracle.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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: UTF-8 -*-
# https://stackoverflow.com/questions/7942520/relationship-between-catalog-schema-user-and-database-instance
import logging
import traceback
import re
import sqlparse
import MySQLdb
import simplejson as json
import threading
import pandas as pd
from common.config import SysConfig
from common.utils.timer import FuncTimer
from sql.utils.sql_utils import (
get_syntax_type,
get_full_sqlitem_list,
get_exec_sqlitem_list,
)
from . import EngineBase
import cx_Oracle
from .models import ResultSet, ReviewSet, ReviewResult
from sql.utils.data_masking import simple_column_mask
logger = logging.getLogger("default")
class OracleEngine(EngineBase):
test_query = "SELECT 1 FROM DUAL"
def __init__(self, instance=None):
super(OracleEngine, self).__init__(instance=instance)
self.service_name = instance.service_name
self.sid = instance.sid
def get_connection(self, db_name=None):
if self.conn:
return self.conn
if self.sid:
dsn = cx_Oracle.makedsn(self.host, self.port, self.sid)
self.conn = cx_Oracle.connect(
self.user, self.password, dsn=dsn, encoding="UTF-8", nencoding="UTF-8"
)
elif self.service_name:
dsn = cx_Oracle.makedsn(
self.host, self.port, service_name=self.service_name
)
self.conn = cx_Oracle.connect(
self.user, self.password, dsn=dsn, encoding="UTF-8", nencoding="UTF-8"
)
else:
raise ValueError("sid 和 dsn 均未填写, 请联系管理页补充该实例配置.")
return self.conn
@property
def name(self):
return "Oracle"
@property
def info(self):
return "Oracle engine"
@property
def auto_backup(self):
"""是否支持备份"""
return True
@staticmethod
def get_backup_connection():
"""备份库连接"""
archer_config = SysConfig()
backup_host = archer_config.get("inception_remote_backup_host")
backup_port = int(archer_config.get("inception_remote_backup_port", 3306))
backup_user = archer_config.get("inception_remote_backup_user")
backup_password = archer_config.get("inception_remote_backup_password")
return MySQLdb.connect(
host=backup_host,
port=backup_port,
user=backup_user,
passwd=backup_password,
charset="utf8mb4",
autocommit=True,
)
@property
def server_version(self):
conn = self.get_connection()
version = conn.version
return tuple([n for n in version.split(".")[:3]])
def get_all_databases(self):
"""获取数据库列表, 返回resultSet 供上层调用, 底层实际上是获取oracle的schema列表"""
return self._get_all_schemas()
def _get_all_databases(self):
"""获取数据库列表, 返回一个ResultSet"""
sql = "select name from v$database"
result = self.query(sql=sql)
db_list = [row[0] for row in result.rows]
result.rows = db_list
return result
def _get_all_instances(self):
"""获取实例列表, 返回一个ResultSet"""
sql = "select instance_name from v$instance"
result = self.query(sql=sql)
instance_list = [row[0] for row in result.rows]
result.rows = instance_list
return result
def _get_all_schemas(self):
"""
获取模式列表
:return:
"""
result = self.query(sql="SELECT username FROM all_users order by username")
sysschema = (
"AUD_SYS",
"ANONYMOUS",
"APEX_030200",
"APEX_PUBLIC_USER",
"APPQOSSYS",
"BI USERS",
"CTXSYS",
"DBSNMP",
"DIP USERS",
"EXFSYS",
"FLOWS_FILES",
"HR USERS",
"IX USERS",
"MDDATA",
"MDSYS",
"MGMT_VIEW",
"OE USERS",
"OLAPSYS",
"ORACLE_OCM",
"ORDDATA",
"ORDPLUGINS",
"ORDSYS",
"OUTLN",
"OWBSYS",
"OWBSYS_AUDIT",
"PM USERS",
"SCOTT",
"SH USERS",
"SI_INFORMTN_SCHEMA",
"SPATIAL_CSW_ADMIN_USR",
"SPATIAL_WFS_ADMIN_USR",
"SYS",
"SYSMAN",
"SYSTEM",
"WMSYS",
"XDB",
"XS$NULL",
"DIP",
"OJVMSYS",
"LBACSYS",
)
schema_list = [row[0] for row in result.rows if row[0] not in sysschema]
result.rows = schema_list
return result
def get_all_tables(self, db_name, **kwargs):
"""获取table 列表, 返回一个ResultSet"""
sql = f"""SELECT table_name FROM all_tables WHERE nvl(tablespace_name, 'no tablespace') NOT IN ('SYSTEM', 'SYSAUX') AND OWNER = '{db_name}' AND IOT_NAME IS NULL AND DURATION IS NULL order by table_name
"""
result = self.query(db_name=db_name, sql=sql)
tb_list = [row[0] for row in result.rows if row[0] not in ["test"]]
result.rows = tb_list
return result
def get_group_tables_by_db(self, db_name):
data = {}
table_list_sql = f"""SELECT table_name, comments FROM dba_tab_comments WHERE owner = '{db_name}'"""
result = self.query(db_name=db_name, sql=table_list_sql)
for row in result.rows:
table_name, table_cmt = row[0], row[1]
if table_name[0] not in data:
data[table_name[0]] = list()
data[table_name[0]].append([table_name, table_cmt])
return data
def get_table_meta_data(self, db_name, tb_name, **kwargs):
"""数据字典页面使用:获取表格的元信息,返回一个dict{column_list: [], rows: []}"""
meta_data_sql = f"""select tcs.TABLE_NAME, --表名
tcs.COMMENTS, --表注释
tcs.TABLE_TYPE, --表/试图 table/view
ss.SEGMENT_TYPE, --段类型 堆表/分区表/IOT表
ts.TABLESPACE_NAME, --表空间
ts.COMPRESSION, --压缩属性
bss.NUM_ROWS, --表中的记录数
bss.BLOCKS, --表中数据所占的数据块数
bss.EMPTY_BLOCKS, --表中的空块数
bss.AVG_SPACE, --数据块中平均的使用空间
bss.CHAIN_CNT, --表中行连接和行迁移的数量
bss.AVG_ROW_LEN, --每条记录的平均长度
bss.LAST_ANALYZED --上次统计信息搜集的时间
from dba_tab_comments tcs
left join dba_segments ss
on ss.owner = tcs.OWNER
and ss.segment_name = tcs.TABLE_NAME
left join dba_tables ts
on ts.OWNER = tcs.OWNER
and ts.TABLE_NAME = tcs.TABLE_NAME
left join DBA_TAB_STATISTICS bss
on bss.OWNER = tcs.owner
and bss.TABLE_NAME = tcs.table_name
WHERE
tcs.OWNER='{db_name}'
AND tcs.TABLE_NAME='{tb_name}'"""
_meta_data = self.query(db_name=db_name, sql=meta_data_sql)
return {"column_list": _meta_data.column_list, "rows": _meta_data.rows[0]}
def get_table_desc_data(self, db_name, tb_name, **kwargs):
"""获取表格字段信息"""
desc_sql = f"""SELECT bcs.COLUMN_NAME "列名",
ccs.comments "列注释" ,
bcs.data_type || case
when bcs.data_precision is not null and nvl(data_scale, 0) > 0 then
'(' || bcs.data_precision || ',' || data_scale || ')'
when bcs.data_precision is not null and nvl(data_scale, 0) = 0 then
'(' || bcs.data_precision || ')'
when bcs.data_precision is null and data_scale is not null then
'(*,' || data_scale || ')'
when bcs.char_length > 0 then
'(' || bcs.char_length || case char_used
when 'B' then
' Byte'
when 'C' then
' Char'
else
null
end || ')'
end "字段类型",
bcs.DATA_DEFAULT "字段默认值",
decode(nullable, 'N', ' NOT NULL') "是否为空",
ics.INDEX_NAME "所属索引",
acs.constraint_type "约束类型"
FROM dba_tab_columns bcs
left join dba_col_comments ccs
on bcs.OWNER = ccs.owner
and bcs.TABLE_NAME = ccs.table_name
and bcs.COLUMN_NAME = ccs.column_name
left join dba_ind_columns ics
on bcs.OWNER = ics.TABLE_OWNER
and bcs.TABLE_NAME = ics.table_name
and bcs.COLUMN_NAME = ics.column_name
left join dba_constraints acs
on acs.owner = ics.TABLE_OWNER
and acs.table_name = ics.TABLE_NAME
and acs.index_name = ics.INDEX_NAME
WHERE
bcs.OWNER='{db_name}'
AND bcs.TABLE_NAME='{tb_name}'
ORDER BY bcs.COLUMN_NAME"""
_desc_data = self.query(db_name=db_name, sql=desc_sql)
return {"column_list": _desc_data.column_list, "rows": _desc_data.rows}
def get_table_index_data(self, db_name, tb_name, **kwargs):
"""获取表格索引信息"""
index_sql = f""" SELECT ais.INDEX_NAME "索引名称",
ais.uniqueness "唯一性",
ais.index_type "索引类型",
ais.compression "压缩属性",
ais.tablespace_name "表空间",
ais.status "状态",
ais.partitioned "分区",
pis.partitioning_type "分区状态",
pis.locality "是否为LOCAL索引",
pis.alignment "前导列索引"
FROM dba_indexes ais
left join DBA_PART_INDEXES pis
on ais.owner = pis.owner
and ais.index_name = pis.index_name
WHERE
ais.owner = '{db_name}'
AND ais.table_name = '{tb_name}'"""
_index_data = self.query(db_name, index_sql)
return {"column_list": _index_data.column_list, "rows": _index_data.rows}
def get_tables_metas_data(self, db_name, **kwargs):
"""获取数据库所有表格信息,用作数据字典导出接口"""
table_metas = []
sql_cols = f""" SELECT bcs.TABLE_NAME TABLE_NAME,
tcs.COMMENTS TABLE_COMMENTS,
bcs.COLUMN_NAME COLUMN_NAME,
bcs.data_type || case
when bcs.data_precision is not null and nvl(data_scale, 0) > 0 then
'(' || bcs.data_precision || ',' || data_scale || ')'
when bcs.data_precision is not null and nvl(data_scale, 0) = 0 then
'(' || bcs.data_precision || ')'
when bcs.data_precision is null and data_scale is not null then
'(*,' || data_scale || ')'
when bcs.char_length > 0 then
'(' || bcs.char_length || case char_used
when 'B' then
' Byte'
when 'C' then
' Char'
else
null
end || ')'
end data_type,
bcs.DATA_DEFAULT,
decode(nullable, 'N', ' NOT NULL') nullable,
t1.index_name,
lcs.comments comments
FROM dba_tab_columns bcs
left join dba_col_comments lcs
on bcs.OWNER = lcs.owner
and bcs.TABLE_NAME = lcs.table_name
and bcs.COLUMN_NAME = lcs.column_name
left join dba_tab_comments tcs
on bcs.OWNER = tcs.OWNER
and bcs.TABLE_NAME = tcs.TABLE_NAME
left join (select acs.OWNER,
acs.TABLE_NAME,
scs.column_name,
acs.index_name
from dba_cons_columns scs
join dba_constraints acs
on acs.constraint_name = scs.constraint_name
and acs.owner = scs.OWNER
where acs.constraint_type = 'P') t1
on t1.OWNER = bcs.OWNER
AND t1.TABLE_NAME = bcs.TABLE_NAME
AND t1.column_name = bcs.COLUMN_NAME
WHERE bcs.OWNER = '{db_name}'
order by bcs.TABLE_NAME, comments"""
cols_req = self.query(sql=sql_cols, close_conn=False).rows
# 给查询结果定义列名,query_engine.query的游标是0 1 2
cols_df = pd.DataFrame(
cols_req,
columns=[
"TABLE_NAME",
"TABLE_COMMENTS",
"COLUMN_NAME",
"COLUMN_TYPE",
"COLUMN_DEFAULT",
"IS_NULLABLE",
"COLUMN_KEY",
"COLUMN_COMMENT",
],
)
# 获得表名称去重
col_list = cols_df.drop_duplicates("TABLE_NAME").to_dict("records")
for cl in col_list:
_meta = dict()
engine_keys = [
{"key": "COLUMN_NAME", "value": "字段名"},
{"key": "COLUMN_TYPE", "value": "数据类型"},
{"key": "COLUMN_DEFAULT", "value": "默认值"},
{"key": "IS_NULLABLE", "value": "允许非空"},
{"key": "COLUMN_KEY", "value": "是否主键"},
{"key": "COLUMN_COMMENT", "value": "备注"},
]
_meta["ENGINE_KEYS"] = engine_keys
_meta["TABLE_INFO"] = {
"TABLE_NAME": cl["TABLE_NAME"],
"TABLE_COMMENTS": cl["TABLE_COMMENTS"],
}
table_name = cl["TABLE_NAME"]
# 查询DataFrame中满足表名的记录,并转为list
_meta["COLUMNS"] = cols_df.query("TABLE_NAME == @table_name").to_dict(
"records"
)
table_metas.append(_meta)
return table_metas
def get_all_objects(self, db_name, **kwargs):
"""获取object_name 列表, 返回一个ResultSet"""
sql = f"""SELECT object_name FROM all_objects WHERE OWNER = '{db_name}' """
result = self.query(db_name=db_name, sql=sql)
tb_list = [row[0] for row in result.rows if row[0] not in ["test"]]
result.rows = tb_list
return result
def get_all_columns_by_tb(self, db_name, tb_name, **kwargs):
"""获取所有字段, 返回一个ResultSet"""
result = self.describe_table(db_name, tb_name)
column_list = [row[0] for row in result.rows]
result.rows = column_list
return result
def describe_table(self, db_name, tb_name, **kwargs):
"""return ResultSet"""
# https://www.thepolyglotdeveloper.com/2015/01/find-tables-oracle-database-column-name/
sql = f"""SELECT
a.column_name,
data_type,
data_length,
nullable,
data_default,
b.comments
FROM all_tab_cols a, all_col_comments b
WHERE a.table_name = b.table_name
and a.owner = b.OWNER
and a.COLUMN_NAME = b.COLUMN_NAME
and a.table_name = '{tb_name}' and a.owner = '{db_name}' order by column_id
"""
result = self.query(db_name=db_name, sql=sql)
return result
def object_name_check(self, db_name=None, object_name=""):
"""获取table 列表, 返回一个ResultSet"""
if "." in object_name:
schema_name = object_name.split(".")[0]
object_name = object_name.split(".")[1]
if '"' in schema_name:
schema_name = schema_name.replace('"', "")
if '"' in object_name:
object_name = object_name.replace('"', "")
else:
object_name = object_name.upper()
else:
schema_name = schema_name.upper()
if '"' in object_name:
object_name = object_name.replace('"', "")
else:
object_name = object_name.upper()
else:
schema_name = db_name
if '"' in object_name:
object_name = object_name.replace('"', "")
else:
object_name = object_name.upper()
sql = f""" SELECT object_name FROM all_objects WHERE OWNER = '{schema_name}' and OBJECT_NAME = '{object_name}' """
result = self.query(db_name=db_name, sql=sql, close_conn=False)
if result.affected_rows > 0:
return True
else:
return False
@staticmethod
def get_sql_first_object_name(sql=""):
"""获取sql文本中的object_name"""
object_name = ""
if re.match(r"^create\s+table\s", sql, re.M | re.IGNORECASE):
object_name = re.match(
r"^create\s+table\s(.+?)(\s|\()", sql, re.M | re.IGNORECASE
).group(1)
elif re.match(r"^create\s+index\s", sql, re.M | re.IGNORECASE):
object_name = re.match(
r"^create\s+index\s(.+?)\s", sql, re.M | re.IGNORECASE
).group(1)
elif re.match(r"^create\s+unique\s+index\s", sql, re.M | re.IGNORECASE):
object_name = re.match(
r"^create\s+unique\s+index\s(.+?)\s", sql, re.M | re.IGNORECASE
).group(1)
elif re.match(r"^create\s+sequence\s", sql, re.M | re.IGNORECASE):
object_name = re.match(
r"^create\s+sequence\s(.+?)(\s|$)", sql, re.M | re.IGNORECASE
).group(1)
elif re.match(r"^alter\s+table\s", sql, re.M | re.IGNORECASE):
object_name = re.match(
r"^alter\s+table\s(.+?)\s", sql, re.M | re.IGNORECASE
).group(1)
elif re.match(r"^create\s+function\s", sql, re.M | re.IGNORECASE):
object_name = re.match(
r"^create\s+function\s(.+?)(\s|\()", sql, re.M | re.IGNORECASE
).group(1)
elif re.match(r"^create\s+view\s", sql, re.M | re.IGNORECASE):
object_name = re.match(
r"^create\s+view\s(.+?)\s", sql, re.M | re.IGNORECASE
).group(1)
elif re.match(r"^create\s+procedure\s", sql, re.M | re.IGNORECASE):
object_name = re.match(
r"^create\s+procedure\s(.+?)\s", sql, re.M | re.IGNORECASE
).group(1)
elif re.match(r"^create\s+package\s+body", sql, re.M | re.IGNORECASE):
object_name = re.match(
r"^create\s+package\s+body\s(.+?)\s", sql, re.M | re.IGNORECASE
).group(1)
elif re.match(r"^create\s+package\s", sql, re.M | re.IGNORECASE):
object_name = re.match(
r"^create\s+package\s(.+?)\s", sql, re.M | re.IGNORECASE
).group(1)
else:
return object_name.strip()
return object_name.strip()
@staticmethod
def check_create_index_table(sql="", object_name_list=None, db_name=""):
object_name_list = object_name_list or set()
if re.match(r"^create\s+index\s", sql):
table_name = re.match(
r"^create\s+index\s+.+\s+on\s(.+?)(\(|\s\()", sql, re.M
).group(1)
if "." not in table_name:
table_name = f"{db_name}.{table_name}"
if table_name in object_name_list:
return True
else:
return False
elif re.match(r"^create\s+unique\s+index\s", sql):
table_name = re.match(
r"^create\s+unique\s+index\s+.+\s+on\s(.+?)(\(|\s\()", sql, re.M
).group(1)
if "." not in table_name:
table_name = f"{db_name}.{table_name}"
if table_name in object_name_list:
return True
else:
return False
else:
return False
@staticmethod
def get_dml_table(sql="", object_name_list=None, db_name=""):
object_name_list = object_name_list or set()
if re.match(r"^update", sql):
table_name = re.match(r"^update\s(.+?)\s", sql, re.M).group(1)
if "." not in table_name:
table_name = f"{db_name}.{table_name}"
if table_name in object_name_list:
return True
else:
return False
elif re.match(r"^delete", sql):
table_name = re.match(r"^delete\s+from\s+([\w-]+)\s*", sql, re.M).group(1)
if "." not in table_name:
table_name = f"{db_name}.{table_name}"
if table_name in object_name_list:
return True
else:
return False
elif re.match(r"^insert\s", sql):
table_name = re.match(
r"^insert\s+((into)|(all\s+into)|(all\s+when\s(.+?)into))\s+(.+?)(\(|\s)",
sql,
re.M,
).group(6)
if "." not in table_name:
table_name = f"{db_name}.{table_name}"
if table_name in object_name_list:
return True
else:
return False
else:
return False
@staticmethod
def where_check(sql=""):
if re.match(r"^update((?!where).)*$|^delete((?!where).)*$", sql):
return True
else:
parsed = sqlparse.parse(sql)[0]
flattened = list(parsed.flatten())
n_skip = 0
flattened = flattened[: len(flattened) - n_skip]
logical_operators = (
"AND",
"OR",
"NOT",
"BETWEEN",
"ORDER BY",
"GROUP BY",
"HAVING",
)
for t in reversed(flattened):
if t.is_keyword:
return True
return False
def explain_check(self, db_name=None, sql="", close_conn=False):
# 使用explain进行支持的SQL语法审核,连接需不中断,防止数据库不断fork进程的大批量消耗
result = {"msg": "", "rows": 0}
try:
conn = self.get_connection()
cursor = conn.cursor()
if db_name:
cursor.execute(f' ALTER SESSION SET CURRENT_SCHEMA = "{db_name}" ')
if re.match(r"^explain", sql, re.I):
sql = sql
else:
sql = f"explain plan for {sql}"
sql = sql.rstrip(";")
cursor.execute(sql)
# 获取影响行数
cursor.execute(f"select CARDINALITY from SYS.PLAN_TABLE$ where id = 0")
rows = cursor.fetchone()
conn.rollback()
if not rows:
result["rows"] = 0
else:
result["rows"] = rows[0]
except Exception as e:
logger.warning(f"Oracle 语句执行报错,语句:{sql},错误信息{traceback.format_exc()}")
result["msg"] = str(e)
finally:
if close_conn:
self.close()
return result
def query_check(self, db_name=None, sql=""):
# 查询语句的检查、注释去除、切分
result = {"msg": "", "bad_query": False, "filtered_sql": sql, "has_star": False}
keyword_warning = ""
star_patter = r"(^|,|\s)\*(\s|\(|$)"
# 删除注释语句,进行语法判断,执行第一条有效sql
try:
sql = sqlparse.format(sql, strip_comments=True)
sql = sqlparse.split(sql)[0]
result["filtered_sql"] = re.sub(r";$", "", sql.strip())
sql_lower = sql.lower()
except IndexError:
result["bad_query"] = True
result["msg"] = "没有有效的SQL语句"
return result
if re.match(r"^select|^with|^explain", sql_lower) is None:
result["bad_query"] = True
result["msg"] = "不支持语法!"
return result
if re.search(star_patter, sql_lower) is not None:
keyword_warning += "禁止使用 * 关键词\n"
result["has_star"] = True
if result.get("bad_query") or result.get("has_star"):
result["msg"] = keyword_warning
return result
def filter_sql(self, sql="", limit_num=0):
sql_lower = sql.lower()
# 对查询sql增加limit限制
if re.match(r"^select|^with", sql_lower) and not (
re.match(r"^select\s+sql_audit.", sql_lower)
and sql_lower.find(" sql_audit where rownum <= ") != -1
):
sql = f"select sql_audit.* from ({sql.rstrip(';')}) sql_audit where rownum <= {limit_num}"
return sql.strip()
def query(self, db_name=None, sql="", limit_num=0, close_conn=True, **kwargs):
"""返回 ResultSet"""
result_set = ResultSet(full_sql=sql)
try:
conn = self.get_connection()
cursor = conn.cursor()
if db_name:
cursor.execute(f' ALTER SESSION SET CURRENT_SCHEMA = "{db_name}" ')
sql = sql.rstrip(";")
# 支持oralce查询SQL执行计划语句
if re.match(r"^explain", sql, re.I):
cursor.execute(sql)
# 重置SQL文本,获取SQL执行计划
sql = f"select PLAN_TABLE_OUTPUT from table(dbms_xplan.display)"
cursor.execute(sql)
fields = cursor.description
if any(x[1] == cx_Oracle.CLOB for x in fields):
rows = [
tuple([(c.read() if type(c) == cx_Oracle.LOB else c) for c in r])
for r in cursor
]
if int(limit_num) > 0:
rows = rows[0 : int(limit_num)]
else:
if int(limit_num) > 0:
rows = cursor.fetchmany(int(limit_num))
else:
rows = cursor.fetchall()
result_set.column_list = [i[0] for i in fields] if fields else []
result_set.rows = [tuple(x) for x in rows]
result_set.affected_rows = len(result_set.rows)
except Exception as e:
logger.warning(f"Oracle 语句执行报错,语句:{sql},错误信息{traceback.format_exc()}")
result_set.error = str(e)
finally:
if close_conn:
self.close()
return result_set
def query_masking(self, db_name=None, sql="", resultset=None):
"""简单字段脱敏规则, 仅对select有效"""
if re.match(r"^select", sql, re.I):
filtered_result = simple_column_mask(self.instance, resultset)
filtered_result.is_masked = True
else:
filtered_result = resultset
return filtered_result
def execute_check(self, db_name=None, sql="", close_conn=True):
"""
上线单执行前的检查, 返回Review set
update by Jan.song 20200302
使用explain对数据修改预计进行检测
"""
config = SysConfig()
check_result = ReviewSet(full_sql=sql)
# explain支持的语法
explain_re = r"^merge|^update|^delete|^insert|^create\s+table|^create\s+index|^create\s+unique\s+index"
# 禁用/高危语句检查
line = 1
# 保存SQL中的新建对象
object_name_list = set()
critical_ddl_regex = config.get("critical_ddl_regex", "")
p = re.compile(critical_ddl_regex)
check_result.syntax_type = 2 # TODO 工单类型 0、其他 1、DDL,2、DML
try:
sqlitemList = get_full_sqlitem_list(sql, db_name)
for sqlitem in sqlitemList:
sql_lower = sqlitem.statement.lower().rstrip(";")
sql_nolower = sqlitem.statement.rstrip(";")
object_name = self.get_sql_first_object_name(sql=sql_lower)
if "." in object_name:
object_name = object_name
else:
object_name = f"""{db_name}.{object_name}"""
object_name_list.add(object_name)
# 禁用语句
if re.match(r"^select|^with|^explain", sql_lower):
result = ReviewResult(
id=line,
errlevel=2,
stagestatus="驳回不支持语句",
errormessage="仅支持DML和DDL语句,查询语句请使用SQL查询功能!",
sql=sqlitem.statement,
)
# 高危语句
elif critical_ddl_regex and p.match(sql_lower.strip()):
result = ReviewResult(
id=line,
errlevel=2,
stagestatus="驳回高危SQL",
errormessage="禁止提交匹配" + critical_ddl_regex + "条件的语句!",
sql=sqlitem.statement,
)
# 驳回未带where数据修改语句,如确实需做全部删除或更新,显示的带上where 1=1
elif re.match(
r"^update((?!where).)*$|^delete((?!where).)*$", sql_lower
):
result = ReviewResult(
id=line,
errlevel=2,
stagestatus="驳回未带where数据修改",
errormessage="数据修改需带where条件!",
sql=sqlitem.statement,
)
# 驳回事务控制,会话控制SQL
elif re.match(r"^set|^rollback|^exit", sql_lower):
result = ReviewResult(
id=line,
errlevel=2,
stagestatus="SQL中不能包含^set|^rollback|^exit",
errormessage="SQL中不能包含^set|^rollback|^exit",
sql=sqlitem.statement,
)
# 通过explain对SQL做语法语义检查
elif re.match(explain_re, sql_lower) and sqlitem.stmt_type == "SQL":
if self.check_create_index_table(
db_name=db_name,
sql=sql_lower,
object_name_list=object_name_list,
):
result = ReviewResult(
id=line,
errlevel=1,
stagestatus="WARNING:新建表的新建索引语句暂无法检测!",
errormessage="WARNING:新建表的新建索引语句暂无法检测!",
stmt_type=sqlitem.stmt_type,
object_owner=sqlitem.object_owner,
object_type=sqlitem.object_type,
object_name=sqlitem.object_name,
sql=sqlitem.statement,
)
elif len(object_name_list) > 0 and self.get_dml_table(
db_name=db_name,
sql=sql_lower,
object_name_list=object_name_list,
):
result = ReviewResult(
id=line,
errlevel=1,
stagestatus="WARNING:新建表的数据修改暂无法检测!",
errormessage="WARNING:新建表的数据修改暂无法检测!",
stmt_type=sqlitem.stmt_type,
object_owner=sqlitem.object_owner,
object_type=sqlitem.object_type,
object_name=sqlitem.object_name,
sql=sqlitem.statement,
)
else:
result_set = self.explain_check(
db_name=db_name, sql=sqlitem.statement, close_conn=False
)
if result_set["msg"]:
result = ReviewResult(
id=line,
errlevel=2,
stagestatus="explain语法检查未通过!",
errormessage=result_set["msg"],
sql=sqlitem.statement,
)
else:
# 对create table\create index\create unique index语法做对象存在性检测
if re.match(
r"^create\s+table|^create\s+index|^create\s+unique\s+index",
sql_lower,
):
object_name = self.get_sql_first_object_name(
sql=sql_nolower
)
# 保存create对象对后续SQL做存在性判断
if "." in object_name:
schema_name = object_name.split(".")[0]
object_name = object_name.split(".")[1]
if '"' in schema_name:
schema_name = schema_name
if '"' not in object_name:
object_name = object_name.upper()
else:
schema_name = schema_name.upper()
if '"' not in object_name:
object_name = object_name.upper()
else:
schema_name = '"' + db_name + '"'
if '"' not in object_name:
object_name = object_name.upper()
object_name = f"""{schema_name}.{object_name}"""
if (
self.object_name_check(
db_name=db_name, object_name=object_name
)
or object_name in object_name_list
):
result = ReviewResult(
id=line,
errlevel=2,
stagestatus=f"""{object_name}对象已经存在!""",
errormessage=f"""{object_name}对象已经存在!""",
sql=sqlitem.statement,
)
else:
object_name_list.add(object_name)
if result_set["rows"] > 1000:
result = ReviewResult(
id=line,
errlevel=1,
stagestatus="影响行数大于1000,请关注",
errormessage="影响行数大于1000,请关注",
sql=sqlitem.statement,
stmt_type=sqlitem.stmt_type,
object_owner=sqlitem.object_owner,
object_type=sqlitem.object_type,
object_name=sqlitem.object_name,
affected_rows=result_set["rows"],
execute_time=0,
)
else:
result = ReviewResult(
id=line,
errlevel=0,
stagestatus="Audit completed",
errormessage="None",
sql=sqlitem.statement,
stmt_type=sqlitem.stmt_type,
object_owner=sqlitem.object_owner,
object_type=sqlitem.object_type,
object_name=sqlitem.object_name,
affected_rows=result_set["rows"],
execute_time=0,
)
else:
if result_set["rows"] > 1000:
result = ReviewResult(
id=line,
errlevel=1,
stagestatus="影响行数大于1000,请关注",
errormessage="影响行数大于1000,请关注",
sql=sqlitem.statement,
stmt_type=sqlitem.stmt_type,
object_owner=sqlitem.object_owner,
object_type=sqlitem.object_type,
object_name=sqlitem.object_name,
affected_rows=result_set["rows"],
execute_time=0,
)
else:
result = ReviewResult(
id=line,
errlevel=0,
stagestatus="Audit completed",
errormessage="None",
sql=sqlitem.statement,
stmt_type=sqlitem.stmt_type,
object_owner=sqlitem.object_owner,
object_type=sqlitem.object_type,
object_name=sqlitem.object_name,
affected_rows=result_set["rows"],
execute_time=0,
)
# 其它无法用explain判断的语句
else:
# 对alter table做对象存在性检查
if re.match(r"^alter\s+table\s", sql_lower):
object_name = self.get_sql_first_object_name(sql=sql_nolower)
if "." in object_name:
schema_name = object_name.split(".")[0]
object_name = object_name.split(".")[1]
if '"' in schema_name:
schema_name = schema_name
if '"' not in object_name:
object_name = object_name.upper()
else:
schema_name = schema_name.upper()
if '"' not in object_name:
object_name = object_name.upper()
else:
schema_name = '"' + db_name + '"'
if '"' not in object_name:
object_name = object_name.upper()
object_name = f"""{schema_name}.{object_name}"""
if (
not self.object_name_check(
db_name=db_name, object_name=object_name
)
and object_name not in object_name_list
):
result = ReviewResult(
id=line,
errlevel=2,
stagestatus=f"""{object_name}对象不存在!""",
errormessage=f"""{object_name}对象不存在!""",
sql=sqlitem.statement,
)
else:
result = ReviewResult(
id=line,
errlevel=1,
stagestatus="当前平台,此语法不支持审核!",
errormessage="当前平台,此语法不支持审核!",
sql=sqlitem.statement,
stmt_type=sqlitem.stmt_type,
object_owner=sqlitem.object_owner,
object_type=sqlitem.object_type,
object_name=sqlitem.object_name,
affected_rows=0,
execute_time=0,
)
# 对create做对象存在性检查
elif re.match(r"^create", sql_lower):
object_name = self.get_sql_first_object_name(sql=sql_nolower)
if "." in object_name:
schema_name = object_name.split(".")[0]
object_name = object_name.split(".")[1]
if '"' in schema_name:
schema_name = schema_name
if '"' not in object_name:
object_name = object_name.upper()
else:
schema_name = schema_name.upper()
if '"' not in object_name:
object_name = object_name.upper()
else:
schema_name = '"' + db_name + '"'
if '"' not in object_name:
object_name = object_name.upper()
object_name = f"""{schema_name}.{object_name}"""
if (
self.object_name_check(
db_name=db_name, object_name=object_name
)
or object_name in object_name_list
):
result = ReviewResult(
id=line,
errlevel=2,
stagestatus=f"""{object_name}对象已经存在!""",
errormessage=f"""{object_name}对象已经存在!""",
sql=sqlitem.statement,
)
else:
object_name_list.add(object_name)
result = ReviewResult(
id=line,
errlevel=1,
stagestatus="当前平台,此语法不支持审核!",
errormessage="当前平台,此语法不支持审核!",
sql=sqlitem.statement,
stmt_type=sqlitem.stmt_type,
object_owner=sqlitem.object_owner,
object_type=sqlitem.object_type,
object_name=sqlitem.object_name,
affected_rows=0,
execute_time=0,
)
else:
result = ReviewResult(
id=line,
errlevel=1,
stagestatus="当前平台,此语法不支持审核!",
errormessage="当前平台,此语法不支持审核!",
sql=sqlitem.statement,
stmt_type=sqlitem.stmt_type,
object_owner=sqlitem.object_owner,
object_type=sqlitem.object_type,
object_name=sqlitem.object_name,