Unverified Commit 05fdd139 authored by 高岩's avatar 高岩 Committed by GitHub

add sql console (#1373)

Co-authored-by: steve <woai1998>
parent afc69733
......@@ -190,7 +190,7 @@ public class DataBaseController {
*/
@GetMapping("/listColumns")
public Result listColumns(@RequestParam Integer id, @RequestParam String schemaName,
@RequestParam String tableName) {
@RequestParam String tableName) {
return Result.succeed(databaseService.listColumns(id, schemaName, tableName), "获取成功");
}
......@@ -207,12 +207,25 @@ public class DataBaseController {
}
}
/**
* 执行sql
*/
@PostMapping("/execSql")
public Result execSql(@RequestBody QueryData queryData) {
JdbcSelectResult jdbcSelectResult = databaseService.execSql(queryData);
if (jdbcSelectResult.isSuccess()) {
return Result.succeed(jdbcSelectResult, "获取成功");
} else {
return Result.failed(jdbcSelectResult, "查询失败");
}
}
/**
* 获取 SqlGeneration
*/
@GetMapping("/getSqlGeneration")
public Result getSqlGeneration(@RequestParam Integer id, @RequestParam String schemaName,
@RequestParam String tableName) {
@RequestParam String tableName) {
return Result.succeed(databaseService.getSqlGeneration(id, schemaName, tableName), "获取成功");
}
......
......@@ -57,6 +57,8 @@ public interface DataBaseService extends ISuperService<DataBase> {
JdbcSelectResult queryData(QueryData queryData);
JdbcSelectResult execSql(QueryData queryData);
SqlGeneration getSqlGeneration(Integer id, String schemaName, String tableName);
List<String> listEnabledFlinkWith();
......
......@@ -157,6 +157,19 @@ public class DataBaseServiceImpl extends SuperServiceImpl<DataBaseMapper, DataBa
return driver.query(queryOption.toString(), null);
}
@Override
public JdbcSelectResult execSql(QueryData queryData) {
DataBase dataBase = getById(queryData.getId());
Asserts.checkNotNull(dataBase, "该数据源不存在!");
Driver driver = Driver.build(dataBase.getDriverConfig());
long startTime = System.currentTimeMillis();
JdbcSelectResult jdbcSelectResult = driver.query(queryData.getSql(), 500);
long endTime = System.currentTimeMillis();
jdbcSelectResult.setTime(endTime - startTime);
jdbcSelectResult.setTotal(jdbcSelectResult.getRowData().size());
return jdbcSelectResult;
}
@Override
public SqlGeneration getSqlGeneration(Integer id, String schemaName, String tableName) {
DataBase dataBase = getById(id);
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.dlink.model;
import lombok.Data;
@Data
public class QueryData {
private String id;
private String schemaName;
private String tableName;
private String sql;
private Option option;
@Data
public class Option {
private String where;
private String order;
private String limitStart;
......
......@@ -233,6 +233,10 @@ export function clearMetaDataTable(id: number) {
export function showTableData(id: number, schemaName: String, tableName: String, option: {}) {
return postAll('api/database/queryData', {id: id, schemaName: schemaName, tableName: tableName, option: option});
}
/*--- 执行sql---*/
export function execDatabaseSql(id: number, sql: String) {
return postAll('api/database/execSql', {id: id, sql: sql});
}
/*--- 刷新 Flink Jobs ---*/
export function showFlinkJobs(clusterId: number) {
......
......@@ -219,7 +219,10 @@ export default {
'pages.datastudio.label.lineage.collapse.field': 'Collapse Field',
'pages.datastudio.label.lineage.expand.lineage': 'Expand Lineage',
'pages.datastudio.label.lineage.collapse.lineage': 'Collapse Lineage',
'pages.metadata.Console': 'SQL Console',
'pages.metadata.help.noSqlSelect': "No Sql Select!",
'pages.metadata.help.selectSql': "please choose sql in editor",
'pages.metadata.help.exec': "exec sql",
'pages.datastudio.label.process': 'Process',
'pages.datastudio.label.history': 'History',
......
......@@ -208,6 +208,10 @@ export default {
'pages.metadata.DataSearch': '数据查询',
'pages.metadata.GenerateSQL': 'SQL 生成',
'pages.metadata.FieldInformation': '字段信息',
'pages.metadata.Console': '控制台',
'pages.metadata.help.noSqlSelect': "未选择任何sql!",
'pages.metadata.help.selectSql': "请在编辑器内选择你要执行的sql",
'pages.metadata.help.exec': "执行选中sql",
'pages.TableData.QueryConditions': '查询条件',
'pages.TableData.sorting': '排序',
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
export function getMysqlKeyWord() {
return ['ADD', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC', 'ASENSITIVE', 'BEFORE', 'BETWEEN',
'BIGINT', 'BINARY', 'BLOB', 'BOTH', 'BY', 'CALL', 'CASCADE', 'CASE', 'CHANGE', 'CHAR', 'CHARACTER',
'CHECK', 'COLLATE', 'COLUMN', 'CONDITION', 'CONNECTION', 'CONSTRAINT', 'CONTINUE', 'CONVERT', 'CREATE',
'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATABASE',
'DATABASES', 'DAY_HOUR', 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT',
'DELAYED', 'DELETE', 'DESC', 'DESCRIBE', 'DETERMINISTIC', 'DISTINCT', 'DISTINCTROW', 'DIV', 'DOUBLE', 'DROP', 'DUAL',
'EACH', 'ELSE', 'ELSEIF', 'ENCLOSED', 'ESCAPED', 'EXISTS', 'EXIT', 'EXPLAIN', 'FALSE', 'FETCH', 'FLOAT', 'FLOAT4', 'FLOAT8',
'FOR', 'FORCE', 'FOREIGN', 'FROM', 'FULLTEXT', 'GOTO', 'GRANT', 'GROUP', 'HAVING', 'HIGH_PRIORITY', 'HOUR_MICROSECOND',
'HOUR_MINUTE', 'HOUR_SECOND', 'IF', 'IGNORE', 'IN', 'INDEX', 'INFILE', 'INNER', 'INOUT', 'INSENSITIVE', 'INSERT', 'INT',
'INT1', 'INT2', 'INT3', 'INT4', 'INT8', 'INTEGER', 'INTERVAL', 'INTO', 'IS', 'ITERATE', 'JOIN', 'KEY', 'KEYS', 'KILL',
'LABEL', 'LEADING', 'LEAVE', 'LEFT', 'LIKE', 'LIMIT', 'LINEAR', 'LINES', 'LOAD', 'LOCALTIME', 'LOCALTIMESTAMP',
'LOCK', 'LONG', 'LONGBLOB', 'LONGTEXT', 'LOOP', 'LOW_PRIORITY', 'MATCH', 'MEDIUMBLOB', 'MEDIUMINT', 'MEDIUMTEXT',
'MIDDLEINT', 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD', 'MODIFIES', 'NATURAL', 'NOT', 'NO_WRITE_TO_BINLOG', 'NULL',
'NUMERIC', 'ON', 'OPTIMIZE', 'OPTION', 'OPTIONALLY', 'OR', 'ORDER', 'OUT', 'OUTER', 'OUTFILE', 'PRECISION', 'PRIMARY',
'PROCEDURE', 'PURGE', 'RAID0', 'RANGE', 'READ', 'READS', 'REAL', 'REFERENCES', 'REGEXP', 'RELEASE', 'RENAME', 'REPEAT',
'REPLACE', 'REQUIRE', 'RESTRICT', 'RETURN', 'REVOKE', 'RIGHT', 'RLIKE', 'SCHEMA', 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT',
'SENSITIVE', 'SEPARATOR', 'SET', 'SHOW', 'SMALLINT', 'SPATIAL', 'SPECIFIC', 'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING',
'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', 'SSL', 'STARTING', 'STRAIGHT_JOIN', 'TABLE', 'TERMINATED', 'THEN',
'TINYBLOB', 'TINYINT', 'TINYTEXT', 'TO', 'TRAILING', 'TRIGGER', 'TRUE', 'UNDO', 'UNION', 'UNIQUE', 'UNLOCK', 'UNSIGNED', 'UPDATE',
'USAGE', 'USE', 'USING', 'UTC_DATE', 'UTC_TIME', 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', 'VARCHAR', 'VARCHARACTER', 'VARYING', 'WHEN',
'WHERE', 'WHILE', 'WITH', 'WRITE', 'X509', 'XOR', 'YEAR_MONTH', 'ZEROFILL'];
}
//暂时使用mysql关键字,后续补充
export function getDorisKeyWord() {
let dorisKey:string[] = []
return mergeKey(dorisKey,getMysqlKeyWord())
}
//暂时使用mysql关键字,后续补充
export function getClickhouseKeyWord() {
let clickhouseKey:string[] = []
return mergeKey(clickhouseKey,getMysqlKeyWord())
}
export function mergeKey(first:string[],second:string[]){
let result:string[] = []
for (let item of first){
result.push(item)
}
for (let item of second){
result.push(item)
}
return result;
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {Alert, Col, Divider, notification, Row, Spin, Table, Tooltip} from 'antd';
import React, {useEffect, useRef, useState} from "react";
import MonacoEditor from "react-monaco-editor";
import {CaretRightOutlined, InfoCircleOutlined} from "@ant-design/icons";
import {execDatabaseSql} from "@/components/Studio/StudioEvent/DDL";
import {ProColumns} from "@ant-design/pro-table/lib/typing";
import * as _monaco from "monaco-editor";
import {l} from "@/utils/intl";
import {CompletionItemInsertTextRule, CompletionItemKind} from "monaco-editor";
import {getClickhouseKeyWord, getDorisKeyWord, getMysqlKeyWord} from "@/pages/DataCenter/MetaData/Console/function";
let provider = {
dispose: () => {
},
};
interface ISuggestions {
label: string;
kind: string;
insertText: string;
detail?: string;
insertTextRules: CompletionItemInsertTextRule
}
const Console = (props: any) => {
const editorInstance: any = useRef<any>();
const monacoInstance: any = useRef();
const {dbId, schemeList, database} = props;
// 表数据
const [tableData, setableData] = useState<{ columns: ProColumns[], rowData: {}[], msg: string }>({
columns: [],
rowData: [],
msg: ""
});
// 加载状态
const [loading, setLoading] = useState<boolean>(false);
const [errMsg, setErrMsg] = useState<{ isErr: boolean, msg: string }>({isErr: false, msg: ""});
//自定义sql提示保存的数组
let metas: [{ name: string, kind: CompletionItemKind }] = [];
let currentDatabase = {type: "mysql"};
useEffect(() => {
for (let db of database) {
if (db.id == dbId) {
currentDatabase = {type: db.type}
console.log(currentDatabase)
}
}
loadDatabaseMeta()
}, [schemeList, database, dbId]);
const editorDidMountHandle = (editor: any, monaco: any) => {
monacoInstance.current = monaco;
editorInstance.current = editor;
reloadCompletion();
};
const loadDatabaseMeta = () => {
//根据数据库不同加载对应数据库的关键字
let keyWords: string[];
console.log(currentDatabase)
switch (currentDatabase.type.toLowerCase()) {
case "doris":
keyWords = getDorisKeyWord()
break
case "mysql":
keyWords = getMysqlKeyWord()
break
case "clickhouse":
keyWords = getClickhouseKeyWord()
break
default:
keyWords = getMysqlKeyWord()
}
//由于自定义sql提示会覆盖原本的sql提示功能,所以需要重新填写
for (let key of keyWords) {
metas.push({name: key, kind: _monaco.languages.CompletionItemKind.Keyword})
}
//加载数据库所有的schema与table添加进sql提示里面,目前还无法做到列级别的提示
for (let database of schemeList) {
metas.push({name: database.name, kind: _monaco.languages.CompletionItemKind.Method})
for (let table of database.tables) {
metas.push({name: table.name, kind: _monaco.languages.CompletionItemKind.Variable})
metas.push({name: `${database.name}.${table.name}`, kind: _monaco.languages.CompletionItemKind.Field})
}
}
}
const reloadCompletion = () => {
provider.dispose();
provider = monacoInstance.current.languages.registerCompletionItemProvider(currentDatabase.type.toLowerCase(), {
provideCompletionItems() {
return {
suggestions: buildSuggestions(),
};
},
});
};
const buildSuggestions = () => {
let suggestions: ISuggestions[] = [];
if (metas) {
for (let item of metas) {
suggestions.push(
{
label: item.name,
kind: item.kind,
insertText: item.name,
insertTextRules: _monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
}
)
}
}
return suggestions;
};
const getSelectionVal = () => {
const selection = editorInstance.current.getSelection() // 获取光标选中的值
const {startLineNumber, endLineNumber, startColumn, endColumn} = selection
const model = editorInstance.current.getModel()
return model.getValueInRange({
startLineNumber,
startColumn,
endLineNumber,
endColumn,
})
}
const execSql = async () => {
let selectSql = getSelectionVal();
if (selectSql == "" || selectSql == undefined) {
notification.warn({
message: l('pages.metadata.help.noSqlSelect'),
description: l('pages.metadata.help.selectSql'),
icon: <InfoCircleOutlined/>,
});
return;
}
setLoading(true);
let temp: { columns: ProColumns[], rowData: {}[], msg: string } = {rowData: [], columns: [], msg: ""}
await execDatabaseSql(dbId, selectSql).then(result => {
if (result.code == 1) {
setErrMsg({isErr: true, msg: result.datas.error})
} else {
setErrMsg({isErr: false, msg: ""})
}
let data = result.datas;
for (const columnsKey in data.columns) {
temp.columns.push({
title: data.columns[columnsKey],
dataIndex: data.columns[columnsKey],
key: data.columns[columnsKey],
ellipsis: true
})
}
for (const row of result.datas.rowData) {
row.key = row.id
temp.rowData.push(row)
}
temp.msg = `Execution Time: ${data.time / 1000} s , Row count: ${data.total}`
if (data.total >= 500) {
temp.msg = `${temp.msg} , row count more than 500, only show top 500`
}
})
setableData(temp);
setLoading(false)
};
return (<>
<div>
<Row>
<Col>
<div style={{
position: "relative", width: "25px",
height: "30vh",
background: "#f0f0f0"
}}>
<Tooltip title={l('pages.metadata.help.exec')}>
<CaretRightOutlined
style={{
color: '#4096ff',
fontSize: "x-large",
textAlign: "center",
position: "absolute",
bottom: "10px",
}}
width={"50px"}
onClick={execSql}
disabled={loading}
shape={"circle"}
/>
</Tooltip>
</div>
</Col>
<Col span={23}>
<MonacoEditor
width={"100%"}
height={"30vh"}
language={currentDatabase.type.toLowerCase()}
theme="vs-dark"
editorDidMount={editorDidMountHandle}
/>
</Col>
</Row>
</div>
<Divider orientation="left"></Divider>
{errMsg.isErr ? (
<Alert
message="Error"
description={errMsg.msg}
type="error"
showIcon
/>
) : tableData.columns.length > 0 ? (
<Alert message={tableData.msg} type="success" showIcon/>
) : <></>
}
<br/>
<div>
<Spin spinning={loading} delay={500}>
<Table
columns={tableData.columns}
dataSource={tableData.rowData}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
}}
scroll={{x: true}}
/>
</Spin>
</div>
</>)
}
;
export default Console;
......@@ -30,7 +30,7 @@ import {
ConsoleSqlOutlined,
DatabaseOutlined,
DownOutlined,
ExclamationCircleOutlined,
ExclamationCircleOutlined, LaptopOutlined,
ReadOutlined,
TableOutlined,
} from '@ant-design/icons';
......@@ -44,6 +44,7 @@ import TableData from '@/pages/DataCenter/MetaData/TableData';
import {FALLBACK, getDBImage} from "@/pages/RegistrationCenter/DataBase/DB";
import Meta from "antd/lib/card/Meta";
import {l} from "@/utils/intl";
import Console from './Console';
const {DirectoryTree} = Tree;
const {TabPane} = Tabs;
......@@ -71,6 +72,7 @@ const MetaDataContainer: React.FC<{}> = (props: any) => {
}]);
const [databaseId, setDatabaseId] = useState<number>();
const [treeData, setTreeData] = useState<{ tables: [], updateTime: string }>({tables: [], updateTime: "none"});
const [schemeList, setSchemeList] = useState<{}>({});
const [row, setRow] = useState<TreeDataNode>();
const [loadingDatabase, setloadingDatabase] = useState(false);
const [tableChecked, setTableChecked] = useState(true);
......@@ -89,7 +91,7 @@ const MetaDataContainer: React.FC<{}> = (props: any) => {
const res = showMetaDataTable(databaseId);
await res.then((result) => {
let tables = result.datas;
setSchemeList(tables)
if (tables) {
for (let i = 0; i < tables.length; i++) {
tables[i].title = tables[i].name;
......@@ -310,6 +312,22 @@ const MetaDataContainer: React.FC<{}> = (props: any) => {
)}
</TabPane>
<TabPane disabled={databaseId==undefined}
tab={
<span>
<LaptopOutlined />
{l('pages.metadata.Console')}
</span>
}
key="Console"
>
{schemeList ? (
<Console dbId={databaseId} schemeList={schemeList} database={database} />
) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
)}
</TabPane>
</Tabs>
</div>
</div>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment