Skip to content

Commit

Permalink
修复sql查询无法使用注释的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
hhyo authored and lihuanhuan committed May 10, 2018
1 parent 4205035 commit 415a7a2
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 150 deletions.
5 changes: 3 additions & 2 deletions sql/dao.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,9 @@ def mysql_query(self, masterHost, masterPort, masterUser, masterPassword, dbName
fields = cursor.description

column_list = []
for i in fields:
column_list.append(i[0])
if fields:
for i in fields:
column_list.append(i[0])
result = {}
result['column_list'] = column_list
result['rows'] = rows
Expand Down
12 changes: 8 additions & 4 deletions sql/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,11 +576,15 @@ def query(request):
loginUserOb = users.objects.get(username=loginUser)

# 过滤注释语句和非查询的语句
sql_list = sqlContent.split('\n')
sqlContent = ''.join(
map(lambda x: re.compile(r'(^--.*|^/\*.*\*/;[\f\n\r\t\v\s]*$)').sub('', x, count=1),
sqlContent.splitlines(1))).strip()
# 去除空行
sqlContent = re.sub('[\r\n\f]{2,}', '\n', sqlContent)

sql_list = sqlContent.strip().split('\n')
for sql in sql_list:
if re.match(r"^(\--|#)", sql):
pass
elif re.match(r"^select|^show.*create.*table|^explain", sql.lower()):
if re.match(r"^select|^show.*create.*table|^explain", sql.lower()):
break
else:
finalResult['status'] = 1
Expand Down
282 changes: 138 additions & 144 deletions sql/static/sqlquery.html
Original file line number Diff line number Diff line change
Expand Up @@ -349,161 +349,155 @@
var table_name = $("#table_name").val();
sqlContent = "show create table " + table_name + ";"
}
//校验SQL
sqlContent = $.trim(sqlContent);
if (sqlContent.toLowerCase().match(/^select/) || sqlContent.toLowerCase().match(/^show.*create.*table/) || sqlContent.toLowerCase().match(/^explain/)) {
$.ajax({
type: "post",
url: "/query/",
dataType: "json",
data: {
cluster_name: $("#cluster_name").val(),
db_name: $("#db_name").val(),
tb_name: $("#table_name").val(),
sql_content: sqlContent,
limit_num: $("#limit_num").val()
},
complete: function () {
$('input[type=button]').removeClass('disabled');
$('input[type=button]').prop('disabled', false);
},
success: function (data) {
if (data.status === 0 || data.status === 2) {
//获取当前的标签页,如果当前不在执行结果页,则默认新增一个页面
var active_li_id = sessionStorage.getItem('active_li_id');

if (active_li_id.match(/^execute_result_tab*/)) {
//查看表结构默认打开新窗口
if (sql === 'show create table') {
tab_add();
n = sessionStorage.getItem('tab_num');
}
else {
var n = active_li_id.split("execute_result_tab")[1];
}
}
else {
//处理SQL,去除注释、空行等
sqlContent = sqlContent.replace(/^--[\f\n\r\t\v\s]+.*|^#[\f\n\r\t\v\s]+.*/g, '');
sqlContent = sqlContent.replace(/[\r\n\f]{2,}/g, '\n');
sqlContent = sqlContent.trim();
//提交请求
$.ajax({
type: "post",
url: "/query/",
dataType: "json",
data: {
cluster_name: $("#cluster_name").val(),
db_name: $("#db_name").val(),
tb_name: $("#table_name").val(),
sql_content: sqlContent,
limit_num: $("#limit_num").val()
},
complete: function () {
$('input[type=button]').removeClass('disabled');
$('input[type=button]').prop('disabled', false);
},
success: function (data) {
if (data.status === 0 || data.status === 2) {
//获取当前的标签页,如果当前不在执行结果页,则默认新增一个页面
var active_li_id = sessionStorage.getItem('active_li_id');

if (active_li_id.match(/^execute_result_tab*/)) {
//查看表结构默认打开新窗口
if (sql === 'show create table') {
tab_add();
n = sessionStorage.getItem('tab_num');
}

var result = data.data;
//查询报错失败
if (result['Error']) {
alertStyle = "alert-danger";
$("#" + ('query_result' + n)).bootstrapTable('destroy').bootstrapTable({
columns: [{
field: 'error',
title: 'Error'
}],
data: [{
error: 'mysql返回异常:' + result['Error']
}]
})
}
//inception检测报错
else if (data.status === 2) {
var errer_info = data.msg;
//替换所有的换行符
errer_info = errer_info.replace(/\r\n/g, "<br>");
errer_info = errer_info.replace(/\n/g, "<br>");
//替换所有的空格
errer_info = errer_info.replace(/\s/g, "&nbsp;");
alertStyle = "alert-danger";
$("#" + ('query_result' + n)).bootstrapTable('destroy').bootstrapTable({
columns: [{
field: 'error',
title: 'Error'
}],
data: [{
error: errer_info
}]
})
else {
var n = active_li_id.split("execute_result_tab")[1];
}
else if (result['column_list']) {
//异步获取要动态生成的列
$.each(result['column_list'], function (i, column) {
columns.push({
"field": i,
"title": column,
"sortable": true,
"formatter": function (value, row, index) {
//return value;
return $('<div/>').text(value).html();
}
});
}
else {
tab_add();
n = sessionStorage.getItem('tab_num');
}

var result = data.data;
//查询报错失败
if (result['Error']) {
alertStyle = "alert-danger";
$("#" + ('query_result' + n)).bootstrapTable('destroy').bootstrapTable({
columns: [{
field: 'error',
title: 'Error'
}],
data: [{
error: 'mysql返回异常:' + result['Error']
}]
})
}
//inception检测报错
else if (data.status === 2) {
var errer_info = data.msg;
//替换所有的换行符
errer_info = errer_info.replace(/\r\n/g, "<br>");
errer_info = errer_info.replace(/\n/g, "<br>");
//替换所有的空格
errer_info = errer_info.replace(/\s/g, "&nbsp;");
alertStyle = "alert-danger";
$("#" + ('query_result' + n)).bootstrapTable('destroy').bootstrapTable({
columns: [{
field: 'error',
title: 'Error'
}],
data: [{
error: errer_info
}]
})
}
else if (result['column_list']) {
//异步获取要动态生成的列
$.each(result['column_list'], function (i, column) {
columns.push({
"field": i,
"title": column,
"sortable": true,
"formatter": function (value, row, index) {
//return value;
return $('<div/>').text(value).html();
}
});
/*//插入选择框
columns.unshift({
title: '',
field: 'checkbox',
checkbox: true
});*/
if (sqlContent.match(/^show.*create.*table/)) {
//初始化表结构显示
$("#" + ("query_result" + n)).bootstrapTable('destroy').bootstrapTable({
data: result['rows'],
columns: [{
title: 'Create Table',
field: 1,
formatter: function (value, row, index) {
var sql = window.sqlFormatter.format(value);
//替换所有的换行符
sql = sql.replace(/\r\n/g, "<br>");
sql = sql.replace(/\n/g, "<br>");
//替换所有的空格
sql = sql.replace(/\s/g, "&nbsp;");
return sql;

}
});
/*//插入选择框
columns.unshift({
title: '',
field: 'checkbox',
checkbox: true
});*/
if (sqlContent.match(/^show.*create.*table/)) {
//初始化表结构显示
$("#" + ("query_result" + n)).bootstrapTable('destroy').bootstrapTable({
data: result['rows'],
columns: [{
title: 'Create Table',
field: 1,
formatter: function (value, row, index) {
var sql = window.sqlFormatter.format(value);
//替换所有的换行符
sql = sql.replace(/\r\n/g, "<br>");
sql = sql.replace(/\n/g, "<br>");
//替换所有的空格
sql = sql.replace(/\s/g, "&nbsp;");
return sql;

}
],
locale: 'zh-CN'
}
);
}
else {
//初始化查询结果
$("#" + ('query_result' + n)).bootstrapTable('destroy').bootstrapTable({
data: result['rows'],
columns: columns,
showExport: true,
exportDataType: "all",
//exportTypes: ['sql'],
exportOptions: {
//ignoreColumn: [0], //忽略某些列的索引数组
fileName: 'export_result' //文件名称设置
},
showColumns: true,
showToggle: true,
clickToSelect: true,
striped: true,
pagination: true,
pageSize: 30,
pageList: [30, 50, 100, 500, 1000],
],
locale: 'zh-CN'
});
}
//执行时间和脱敏时间赋值
$("#" + ('time') + n).text(result['cost_time'] + ' sec');
$("#" + ('masking_time') + n).text(result['masking_cost_time'] + ' sec');
}
);
}
else {
//初始化查询结果
$("#" + ('query_result' + n)).bootstrapTable('destroy').bootstrapTable({
data: result['rows'],
columns: columns,
showExport: true,
exportDataType: "all",
//exportTypes: ['sql'],
exportOptions: {
//ignoreColumn: [0], //忽略某些列的索引数组
fileName: 'export_result' //文件名称设置
},
showColumns: true,
showToggle: true,
clickToSelect: true,
striped: true,
pagination: true,
pageSize: 30,
pageList: [30, 50, 100, 500, 1000],
locale: 'zh-CN'
});
}
} else {
alert("status: " + data.status + "\nmsg: " + data.msg);
//执行时间和脱敏时间赋值
$("#" + ('time') + n).text(result['cost_time'] + ' sec');
$("#" + ('masking_time') + n).text(result['masking_cost_time'] + ' sec');
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
} else {
alert("status: " + data.status + "\nmsg: " + data.msg);
}
})
;
}
else {
alert('仅支持^select|^show.*create.*table|^explain语法,请联系管理员!');
$('input[type=button]').removeClass('disabled');
$('input[type=button]').prop('disabled', false);
}

},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
<!-- common -->
Expand Down

0 comments on commit 415a7a2

Please sign in to comment.