Skip to content

Commit

Permalink
mysql查询支持将Binary格式转换为HEX展示 #1772
Browse files Browse the repository at this point in the history
  • Loading branch information
hhyo committed Sep 19, 2022
1 parent 8cdb232 commit 5ef43df
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 7 deletions.
2 changes: 2 additions & 0 deletions sql/engines/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ def __init__(
status=None,
affected_rows=0,
column_list=None,
column_type=None,
**kwargs
):
self.full_sql = full_sql
Expand All @@ -145,6 +146,7 @@ def __init__(
# rows 为普通列表
self.rows = rows or []
self.column_list = column_list if column_list else []
self.column_type = column_type if column_type else []
self.status = status
self.affected_rows = affected_rows

Expand Down
65 changes: 58 additions & 7 deletions sql/engines/mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,38 @@

logger = logging.getLogger("default")

# https://github.com/mysql/mysql-connector-python/blob/master/lib/mysql/connector/constants.py#L168
column_types_map = {
0: "DECIMAL",
1: "TINY",
2: "SHORT",
3: "LONG",
4: "FLOAT",
5: "DOUBLE",
6: "NULL",
7: "TIMESTAMP",
8: "LONGLONG",
9: "INT24",
10: "DATE",
11: "TIME",
12: "DATETIME",
13: "YEAR",
14: "NEWDATE",
15: "VARCHAR",
16: "BIT",
245: "JSON",
246: "NEWDECIMAL",
247: "ENUM",
248: "SET",
249: "TINY_BLOB",
250: "MEDIUM_BLOB",
251: "LONG_BLOB",
252: "BLOB",
253: "VAR_STRING",
254: "STRING",
255: "GEOMETRY",
}


class MysqlEngine(EngineBase):
test_query = "SELECT 1"
Expand Down Expand Up @@ -120,7 +152,7 @@ def get_all_databases(self):
row[0]
for row in result.rows
if row[0]
not in ("information_schema", "performance_schema", "mysql", "test", "sys")
not in ("information_schema", "performance_schema", "mysql", "test", "sys")
]
result.rows = db_list
return result
Expand Down Expand Up @@ -277,6 +309,22 @@ def describe_table(self, db_name, tb_name, **kwargs):
result = self.query(db_name=db_name, sql=sql)
return result

@staticmethod
def result_set_binary_as_hex(result_set):
"""处理ResultSet,将binary处理成hex"""
new_rows, hex_column_index = [], []
for idx, _type in enumerate(result_set.column_type):
if _type in ['TINY_BLOB', 'MEDIUM_BLOB', 'LONG_BLOB', 'BLOB']:
hex_column_index.append(idx)
if hex_column_index:
for row in result_set.rows:
row = list(row)
for index in hex_column_index:
row[index] = row[index].hex() if row[index] else row[index]
new_rows.append(row)
result_set.rows = tuple(new_rows)
return result_set

def query(self, db_name=None, sql="", limit_num=0, close_conn=True, **kwargs):
"""返回 ResultSet"""
result_set = ResultSet(full_sql=sql)
Expand All @@ -298,8 +346,11 @@ def query(self, db_name=None, sql="", limit_num=0, close_conn=True, **kwargs):
fields = cursor.description

result_set.column_list = [i[0] for i in fields] if fields else []
result_set.column_type = [column_types_map.get(i[1], '') for i in fields] if fields else []
result_set.rows = rows
result_set.affected_rows = effect_row
if kwargs.get('binary_as_hex'):
result_set = self.result_set_binary_as_hex(result_set)
except Exception as e:
logger.warning(f"MySQL语句执行报错,语句:{sql},错误信息{traceback.format_exc()}")
result_set.error = str(e)
Expand Down Expand Up @@ -333,13 +384,13 @@ def query_check(self, db_name=None, sql=""):
result["msg"] = explain_result.error
# 不应该查看mysql.user表
if re.match(
".*(\\s)+(mysql|`mysql`)(\\s)*\\.(\\s)*(user|`user`)((\\s)*|;).*",
sql.lower().replace("\n", ""),
".*(\\s)+(mysql|`mysql`)(\\s)*\\.(\\s)*(user|`user`)((\\s)*|;).*",
sql.lower().replace("\n", ""),
) or (
db_name == "mysql"
and re.match(
".*(\\s)+(user|`user`)((\\s)*|;).*", sql.lower().replace("\n", "")
)
db_name == "mysql"
and re.match(
".*(\\s)+(user|`user`)((\\s)*|;).*", sql.lower().replace("\n", "")
)
):
result["bad_query"] = True
result["msg"] = "您无权查看该表"
Expand Down

0 comments on commit 5ef43df

Please sign in to comment.