Unverified Commit a08fb07a authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Feature]Add json to sql tool (#2466)

* add_json_to_sql_tool
parent da04622e
/*
*
* 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 org.dinky.controller;
import org.dinky.data.result.Result;
import org.dinky.tools.JsonToSqlConvent;
import java.util.Map;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@Api(tags = "Tools Controller")
@RequestMapping("/api/tools")
@RequiredArgsConstructor
public class ToolsController {
@PostMapping("/jsonToFlinkSql")
public Result<String> jsonToSql(@RequestBody Map<String, String> data) {
return Result.succeed(JsonToSqlConvent.commonDataJson(data.get("data")), "");
}
}
/*
*
* 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 org.dinky.tools;
import java.math.BigDecimal;
import com.alibaba.fastjson2.JSON;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
public class JsonToSqlConvent {
/**
* Convert ordinary json data to sql
*
* @param jsonStr json str
*/
public static String commonDataJson(String jsonStr) {
if (!JSON.isValid(jsonStr)) {
return "";
}
JSONObject data = JSONUtil.parseObj(jsonStr);
StringBuilder sb = new StringBuilder();
commonDataConvert(data, sb, 1);
return sb.toString();
}
/**
* Convert ordinary json data to sql
*
* @param data json object
* @param sb string builder
* @param layerNum layer number
*/
private static void commonDataConvert(JSONObject data, StringBuilder sb, int layerNum) {
for (int i = 0; i < data.keySet().size(); i++) {
String key = CollUtil.get(data.keySet(), i);
String endFlag = i == data.keySet().size() - 1 ? "\n" : ",\n";
Object o = data.get(key);
if (o instanceof JSONObject) {
sb.append(StrUtil.repeat("\t", layerNum))
.append("`")
.append(key)
.append("` ROW(\n");
commonDataConvert((JSONObject) o, sb, layerNum + 1);
sb.append(StrUtil.repeat("\t", layerNum)).append(")").append(endFlag);
} else if (o instanceof JSONArray) {
sb.append(StrUtil.repeat("\t", layerNum))
.append("`")
.append(key)
.append("` ARRAY<");
if (((JSONArray) o).isEmpty()) {
sb.append("STRING>").append(endFlag);
continue;
}
Object o1 = ((JSONArray) o).get(0);
if (o1 instanceof JSONObject) {
sb.append("ROW(\n");
commonDataConvert((JSONObject) o1, sb, layerNum + 1);
sb.append(StrUtil.repeat("\t", layerNum)).append(")>").append(endFlag);
} else {
String type = getBaseType(o1);
sb.append(type).append(">").append(endFlag);
}
} else {
String type = getBaseType(o);
sb.append(StrUtil.repeat("\t", layerNum))
.append("`")
.append(key)
.append("` ")
.append(type)
.append(endFlag);
}
}
}
/**
* Get the base type of the object
*
* @param o object
* @return base type
*/
private static String getBaseType(Object o) {
String type = "null";
if (o instanceof Integer) {
type = "BIGINT";
} else if (o instanceof Boolean) {
type = "BOOLEAN";
} else if (o instanceof String) {
type = "STRING";
} else if (o instanceof BigDecimal) {
type = "DOUBLE";
}
return type;
}
}
...@@ -25,7 +25,7 @@ import { convertCodeEditTheme } from '@/utils/function'; ...@@ -25,7 +25,7 @@ import { convertCodeEditTheme } from '@/utils/function';
import { Editor, useMonaco } from '@monaco-editor/react'; import { Editor, useMonaco } from '@monaco-editor/react';
import { editor } from 'monaco-editor'; import { editor } from 'monaco-editor';
import { EditorLanguage } from 'monaco-editor/esm/metadata'; import { EditorLanguage } from 'monaco-editor/esm/metadata';
import { useEffect, useState } from 'react'; import {CSSProperties, useEffect, useState} from 'react';
import FullscreenBtn from '../FullscreenBtn'; import FullscreenBtn from '../FullscreenBtn';
// loader.config({monaco}); // loader.config({monaco});
...@@ -47,7 +47,7 @@ export type CodeShowFormProps = { ...@@ -47,7 +47,7 @@ export type CodeShowFormProps = {
showFloatButton?: boolean; showFloatButton?: boolean;
refreshLogCallback?: () => void; refreshLogCallback?: () => void;
fullScreenBtn?: boolean; fullScreenBtn?: boolean;
style?: React.CSSProperties; style?: CSSProperties;
}; };
const CodeShow = (props: CodeShowFormProps) => { const CodeShow = (props: CodeShowFormProps) => {
...@@ -215,7 +215,6 @@ const CodeShow = (props: CodeShowFormProps) => { ...@@ -215,7 +215,6 @@ const CodeShow = (props: CodeShowFormProps) => {
value={loading ? 'loading...' : code} value={loading ? 'loading...' : code}
language={language} language={language}
options={{ options={{
...options,
scrollBeyondLastLine: false, scrollBeyondLastLine: false,
readOnly: true, readOnly: true,
wordWrap: autoWrap, wordWrap: autoWrap,
...@@ -245,7 +244,8 @@ const CodeShow = (props: CodeShowFormProps) => { ...@@ -245,7 +244,8 @@ const CodeShow = (props: CodeShowFormProps) => {
verticalScrollbarSize: 8, verticalScrollbarSize: 8,
horizontalScrollbarSize: 8, horizontalScrollbarSize: 8,
arrowSize: 30 arrowSize: 30
} },
...options,
}} }}
onMount={editorDidMount} onMount={editorDidMount}
theme={convertCodeEditTheme()} theme={convertCodeEditTheme()}
......
...@@ -95,5 +95,6 @@ export default { ...@@ -95,5 +95,6 @@ export default {
'menu.datastudio.history': 'History', 'menu.datastudio.history': 'History',
'menu.datastudio.table-data': 'Table Data', 'menu.datastudio.table-data': 'Table Data',
'menu.datastudio.tool.text-comparison': 'Text Comparison' 'menu.datastudio.tool.text-comparison': 'Text Comparison',
'menu.datastudio.tool.jsonToSql': 'JSON TO Flink-SQL'
}; };
...@@ -94,5 +94,7 @@ export default { ...@@ -94,5 +94,7 @@ export default {
'menu.datastudio.history': '历史', 'menu.datastudio.history': '历史',
'menu.datastudio.table-data': '表数据', 'menu.datastudio.table-data': '表数据',
'menu.datastudio.tool.text-comparison': '文本比对' 'menu.datastudio.tool.text-comparison': '文本比对',
'menu.datastudio.tool.jsonToSql': 'JSON转Flink-SQL'
}; };
import React, {useState} from "react";
import {Button, Space} from "antd";
import CodeShow from "@/components/CustomEditor/CodeShow";
import useThemeValue from "@/hooks/useThemeValue";
import {jsonToSql} from "@/pages/DataStudio/BottomContainer/Tools/JsonToSql/service";
import {convertCodeEditTheme} from "@/utils/function";
import {connect} from "@@/exports";
import {StateType} from "@/pages/DataStudio/model";
import CodeEdit from "@/components/CustomEditor/CodeEdit";
const padding = 10;
const JsonToSql: React.FC = (props:connect) => {
const {height} = props;
const maxHeight=height-36-(padding*2)-32-12;
const themeValue = useThemeValue();
const border = `1px solid ${themeValue.borderColor}`;
const [jsonData, setJsonData] = useState("");
const [sqlData, setSqlData] = useState("");
return (
<div style={{padding: padding}}>
<Space>
<Button
children={"Convert"}
onClick={() => {
jsonToSql({"data": jsonData}).then(setSqlData)
}}
/>
</Space>
<div style={{display: "flex", paddingBlockStart: padding}}>
<div style={{width: "50%", border}}>
<CodeEdit height={maxHeight+"px"} code={jsonData} language={"json"} theme={convertCodeEditTheme()} onChange={(x) => {
setJsonData(x ?? "");
}}/>
</div>
<div style={{width: "50%"}}>
<CodeShow height={maxHeight} code={sqlData} language={"json"} style={{border}}
options={{minimap: true}}/>
</div>
</div>
</div>
)
}
export default connect(({ Studio }: { Studio: StateType }) => ({
height: Studio.bottomContainer.height
}))(JsonToSql);
import {postAll} from "@/services/api";
export async function jsonToSql(params: any) {
return (await postAll('/api/tools/jsonToFlinkSql', params)).data;
}
\ No newline at end of file
...@@ -51,7 +51,7 @@ import { ...@@ -51,7 +51,7 @@ import {
PlusCircleOutlined, PlusCircleOutlined,
PlusOutlined, PlusOutlined,
ReloadOutlined, ReloadOutlined,
RightSquareOutlined, RightSquareOutlined, RotateRightOutlined,
SettingOutlined, SettingOutlined,
ShrinkOutlined, ShrinkOutlined,
TableOutlined, TableOutlined,
...@@ -59,6 +59,7 @@ import { ...@@ -59,6 +59,7 @@ import {
} from '@ant-design/icons'; } from '@ant-design/icons';
import { DiffEditor } from '@monaco-editor/react'; import { DiffEditor } from '@monaco-editor/react';
import { ReactNode } from 'react'; import { ReactNode } from 'react';
import JsonToSql from "@/pages/DataStudio/BottomContainer/Tools/JsonToSql";
export const LeftSide = [ export const LeftSide = [
{ {
...@@ -216,38 +217,10 @@ export const LeftBottomMoreTabs: { [c: string]: TabProp[] } = { ...@@ -216,38 +217,10 @@ export const LeftBottomMoreTabs: { [c: string]: TabProp[] } = {
) )
}, },
{ {
key: 'menu.datastudio.tool.datax2', key: 'menu.datastudio.tool.jsonToSql',
icon: <ToolOutlined />, icon:<RotateRightOutlined />,
label: 'menu.datastudio.tool.datax2', label: l("menu.datastudio.tool.jsonToSql"),
children: <div>datax2</div> children: <JsonToSql />
}
],
'menu.datastudio.tool2': [
{
key: 'menu.datastudio.tool.text-comparison',
icon: <ToolOutlined />,
label: 'menu.datastudio.tool.text-comparison',
children: (
<DiffEditor
height={'95%'}
options={{
readOnly: true,
selectOnLineNumbers: true,
lineDecorationsWidth: 20,
mouseWheelZoom: true,
automaticLayout: true
}}
language={'sql'}
original={''}
modified={''}
/>
)
},
{
key: 'menu.datastudio.tool.datax2',
icon: <ToolOutlined />,
label: 'menu.datastudio.tool.datax2',
children: <div>datax2</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