Unverified Commit a387db97 authored by 高岩's avatar 高岩 Committed by GitHub

Feature support metadata cache to memory or redis (#1051)

* Fix entity class deserialization error

* Added metadata cache function, which support memory or redis

* add time filed on Result return

* Redesign the metadata UI and support caching

* fix merge

* Add scroll bar when database exceeds seven

* Add apache Licensed

Co-authored-by: steve <woai1998>
parent 973ee343
...@@ -127,10 +127,10 @@ ...@@ -127,10 +127,10 @@
<artifactId>sa-token-spring-boot-starter</artifactId> <artifactId>sa-token-spring-boot-starter</artifactId>
</dependency> </dependency>
<!-- sa-token 持久化 --> <!-- sa-token 持久化 -->
<!-- <dependency>--> <dependency>
<!-- <groupId>org.springframework.boot</groupId>--> <groupId>org.springframework.boot</groupId>
<!-- <artifactId>spring-boot-starter-data-redis</artifactId>--> <artifactId>spring-boot-starter-data-redis</artifactId>
<!-- </dependency>--> </dependency>
<!-- <dependency>--> <!-- <dependency>-->
<!-- <groupId>cn.dev33</groupId>--> <!-- <groupId>cn.dev33</groupId>-->
<!-- <artifactId>sa-token-dao-redis-jackson</artifactId>--> <!-- <artifactId>sa-token-dao-redis-jackson</artifactId>-->
......
...@@ -21,6 +21,7 @@ package com.dlink; ...@@ -21,6 +21,7 @@ package com.dlink;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.EnableTransactionManagement;
/** /**
...@@ -31,6 +32,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; ...@@ -31,6 +32,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
*/ */
@EnableTransactionManagement @EnableTransactionManagement
@SpringBootApplication @SpringBootApplication
@EnableCaching
public class Dlink { public class Dlink {
public static void main(String[] args) { public static void main(String[] args) {
......
...@@ -23,6 +23,7 @@ import com.dlink.model.CodeEnum; ...@@ -23,6 +23,7 @@ import com.dlink.model.CodeEnum;
import java.io.Serializable; import java.io.Serializable;
import cn.hutool.core.date.DateTime;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
...@@ -41,6 +42,7 @@ public class Result<T> implements Serializable { ...@@ -41,6 +42,7 @@ public class Result<T> implements Serializable {
private T datas; private T datas;
private Integer code; private Integer code;
private String msg; private String msg;
private String time;
public static <T> Result<T> succeed(String msg) { public static <T> Result<T> succeed(String msg) {
return of(null, CodeEnum.SUCCESS.getCode(), msg); return of(null, CodeEnum.SUCCESS.getCode(), msg);
...@@ -55,7 +57,7 @@ public class Result<T> implements Serializable { ...@@ -55,7 +57,7 @@ public class Result<T> implements Serializable {
} }
public static <T> Result<T> of(T datas, Integer code, String msg) { public static <T> Result<T> of(T datas, Integer code, String msg) {
return new Result<>(datas, code, msg); return new Result<>(datas, code, msg,new DateTime().toString());
} }
public static <T> Result<T> failed(String msg) { public static <T> Result<T> failed(String msg) {
......
/*
*
* 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.configure;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* CacheCoonfigure
*
* @author ikiler
* @since 2022/09/24 11:23
*/
@Configuration
public class CacheConfigure {
/**
* 配置Redis缓存注解的value序列化方式
*/
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
//序列化为json
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json())
)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
}
// /**
// * 配置RedisTemplate的序列化方式
// */
// @Bean
// public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
// RedisTemplate redisTemplate = new RedisTemplate();
// redisTemplate.setConnectionFactory(factory);
// // 指定key的序列化方式:string
// redisTemplate.setKeySerializer(RedisSerializer.string());
// // 指定value的序列化方式:json
// redisTemplate.setValueSerializer(RedisSerializer.json());
// return redisTemplate;
// }
}
...@@ -35,6 +35,8 @@ import java.util.List; ...@@ -35,6 +35,8 @@ import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
...@@ -167,11 +169,21 @@ public class DataBaseController { ...@@ -167,11 +169,21 @@ public class DataBaseController {
/** /**
* 获取元数据的表 * 获取元数据的表
*/ */
@Cacheable(cacheNames = "metadata_schema",key = "#id")
@GetMapping("/getSchemasAndTables") @GetMapping("/getSchemasAndTables")
public Result getSchemasAndTables(@RequestParam Integer id) { public Result getSchemasAndTables(@RequestParam Integer id) {
return Result.succeed(databaseService.getSchemasAndTables(id), "获取成功"); return Result.succeed(databaseService.getSchemasAndTables(id), "获取成功");
} }
/**
* 清除元数据表的缓存
*/
@CacheEvict(cacheNames = "metadata_schema",key = "#id")
@GetMapping("/unCacheSchemasAndTables")
public Result unCacheSchemasAndTables(@RequestParam Integer id) {
return Result.succeed("clear cache", "success");
}
/** /**
* 获取元数据的指定表的列 * 获取元数据的指定表的列
*/ */
......
...@@ -11,6 +11,20 @@ spring: ...@@ -11,6 +11,20 @@ spring:
matching-strategy: ant_path_matcher matching-strategy: ant_path_matcher
main: main:
allow-circular-references: true allow-circular-references: true
# 默认使用内存缓存元数据信息,
# dlink支持redis缓存,如有需要请把simple改为redis,并打开下面的redis连接配置
# 子配置项可以按需要打开或自定义配置
cache:
type: simple
## 如果type配置为redis,则该项可按需配置
# redis:
## 是否缓存空值,保存默认即可
# cache-null-values: false
## 缓存过期时间,24小时
# time-to-live: 86400
# flyway: # flyway:
# enabled: false # enabled: false
# clean-disabled: true # clean-disabled: true
......
...@@ -45,6 +45,12 @@ public class Schema implements Serializable, Comparable<Schema> { ...@@ -45,6 +45,12 @@ public class Schema implements Serializable, Comparable<Schema> {
private List<String> userFunctions = new ArrayList<>(); private List<String> userFunctions = new ArrayList<>();
private List<String> modules = new ArrayList<>(); private List<String> modules = new ArrayList<>();
/**
* 需要保留一个空构造方法,否则序列化有问题
* */
public Schema() {
}
public Schema(String name) { public Schema(String name) {
this.name = name; this.name = name;
} }
......
...@@ -22,6 +22,7 @@ package com.dlink.model; ...@@ -22,6 +22,7 @@ package com.dlink.model;
import com.dlink.assertion.Asserts; import com.dlink.assertion.Asserts;
import com.dlink.utils.SqlUtil; import com.dlink.utils.SqlUtil;
import java.beans.Transient;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
...@@ -75,10 +76,12 @@ public class Table implements Serializable, Comparable<Table> { ...@@ -75,10 +76,12 @@ public class Table implements Serializable, Comparable<Table> {
this.columns = columns; this.columns = columns;
} }
@Transient
public String getSchemaTableName() { public String getSchemaTableName() {
return Asserts.isNullString(schema) ? name : schema + "." + name; return Asserts.isNullString(schema) ? name : schema + "." + name;
} }
@Transient
public String getSchemaTableNameWithUnderline() { public String getSchemaTableNameWithUnderline() {
return Asserts.isNullString(schema) ? name : schema + "_" + name; return Asserts.isNullString(schema) ? name : schema + "_" + name;
} }
...@@ -100,6 +103,7 @@ public class Table implements Serializable, Comparable<Table> { ...@@ -100,6 +103,7 @@ public class Table implements Serializable, Comparable<Table> {
return new Table(name, schema, columns); return new Table(name, schema, columns);
} }
@Transient
public String getFlinkTableWith(String flinkConfig) { public String getFlinkTableWith(String flinkConfig) {
String tableWithSql = ""; String tableWithSql = "";
if (Asserts.isNotNullString(flinkConfig)) { if (Asserts.isNotNullString(flinkConfig)) {
...@@ -109,10 +113,12 @@ public class Table implements Serializable, Comparable<Table> { ...@@ -109,10 +113,12 @@ public class Table implements Serializable, Comparable<Table> {
return tableWithSql; return tableWithSql;
} }
@Transient
public String getFlinkTableSql(String flinkConfig) { public String getFlinkTableSql(String flinkConfig) {
return getFlinkDDL(flinkConfig, name); return getFlinkDDL(flinkConfig, name);
} }
@Transient
public String getFlinkDDL(String flinkConfig, String tableName) { public String getFlinkDDL(String flinkConfig, String tableName) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("CREATE TABLE IF NOT EXISTS " + tableName + " (\n"); sb.append("CREATE TABLE IF NOT EXISTS " + tableName + " (\n");
...@@ -162,6 +168,7 @@ public class Table implements Serializable, Comparable<Table> { ...@@ -162,6 +168,7 @@ public class Table implements Serializable, Comparable<Table> {
return sb.toString(); return sb.toString();
} }
@Transient
public String getFlinkTableSql(String catalogName, String flinkConfig) { public String getFlinkTableSql(String catalogName, String flinkConfig) {
StringBuilder sb = new StringBuilder("DROP TABLE IF EXISTS "); StringBuilder sb = new StringBuilder("DROP TABLE IF EXISTS ");
String fullSchemaName = catalogName + "." + schema + "." + name; String fullSchemaName = catalogName + "." + schema + "." + name;
...@@ -213,6 +220,7 @@ public class Table implements Serializable, Comparable<Table> { ...@@ -213,6 +220,7 @@ public class Table implements Serializable, Comparable<Table> {
return sb.toString(); return sb.toString();
} }
@Transient
public String getSqlSelect(String catalogName) { public String getSqlSelect(String catalogName) {
StringBuilder sb = new StringBuilder("SELECT\n"); StringBuilder sb = new StringBuilder("SELECT\n");
for (int i = 0; i < columns.size(); i++) { for (int i = 0; i < columns.size(); i++) {
...@@ -239,6 +247,7 @@ public class Table implements Serializable, Comparable<Table> { ...@@ -239,6 +247,7 @@ public class Table implements Serializable, Comparable<Table> {
return sb.toString(); return sb.toString();
} }
@Transient
public String getCDCSqlInsert(String targetName, String sourceName) { public String getCDCSqlInsert(String targetName, String sourceName) {
StringBuilder sb = new StringBuilder("INSERT INTO "); StringBuilder sb = new StringBuilder("INSERT INTO ");
sb.append(targetName); sb.append(targetName);
......
...@@ -222,6 +222,11 @@ export function showAlertGroup(dispatch: any) { ...@@ -222,6 +222,11 @@ export function showAlertGroup(dispatch: any) {
export function showMetaDataTable(id: number) { export function showMetaDataTable(id: number) {
return getData('api/database/getSchemasAndTables', {id: id}); return getData('api/database/getSchemasAndTables', {id: id});
} }
/*--- 清理 元数据表缓存 ---*/
export function clearMetaDataTable(id: number) {
return getData('api/database/unCacheSchemasAndTables', {id: id});
}
/*--- 刷新 数据表样例数据 ---*/ /*--- 刷新 数据表样例数据 ---*/
export function showTableData(id: number,schemaName:String,tableName:String,option:{}) { export function showTableData(id: number,schemaName:String,tableName:String,option:{}) {
return postAll('api/database/queryData', {id: id,schemaName:schemaName,tableName:tableName,option:option}); return postAll('api/database/queryData', {id: id,schemaName:schemaName,tableName:tableName,option:option});
......
...@@ -32,6 +32,8 @@ export interface TreeDataNode extends DataNode { ...@@ -32,6 +32,8 @@ export interface TreeDataNode extends DataNode {
taskId:number; taskId:number;
parentId:number; parentId:number;
path:string[]; path:string[];
schema:string;
table:string;
} }
export function convertToTreeData(data:TreeDataNode[], pid:number,path?:string[]) { export function convertToTreeData(data:TreeDataNode[], pid:number,path?:string[]) {
......
/*
*
* 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.
*
*/
.margin_10{ .margin_10{
margin: 10px; margin: 10px;
......
/*
*
* 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 {useEffect, useState} from "react"; import {useEffect, useState} from "react";
import {Alert, AutoComplete, Button, Col, Input, Row, Spin, Table, Tooltip} from "antd"; import {Alert, AutoComplete, Button, Col, Input, Row, Spin, Table, Tooltip} from "antd";
import {showTableData} from "@/components/Studio/StudioEvent/DDL"; import {showTableData} from "@/components/Studio/StudioEvent/DDL";
import styles from './index.less'; import styles from './index.less';
import { SearchOutlined} from "@ant-design/icons"; import {SearchOutlined} from "@ant-design/icons";
import Divider from "antd/es/divider"; import Divider from "antd/es/divider";
const TableData = (props: any) => { const TableData = (props: any) => {
// 数据库id,数据库名称,表名称 // 数据库id,数据库名称,表名称
const {dbId, table, schema,rows} = props; const {dbId, table, schema} = props;
// 表数据 // 表数据
const [tableData, setableData] = useState<{ columns: {}[],rowData: {}[] }>({columns: [], rowData: []}); const [tableData, setableData] = useState<{ columns: {}[], rowData: {}[] }>({columns: [], rowData: []});
// 加载状态 // 加载状态
const [loading, setLoading] = useState<boolean>(false); const [loading, setLoading] = useState<boolean>(false);
// 列名和列信息数据 // 列名和列信息数据
const [columns, setColumns] = useState<string[]>([]); const [columns, setColumns] = useState<string[]>([]);
const [errMsg, setErrMsg] = useState<{isErr:boolean,msg:string}>({isErr:false,msg:""}); const [errMsg, setErrMsg] = useState<{ isErr: boolean, msg: string }>({isErr: false, msg: ""});
//使用多选框进行自由列选择,屏蔽不需要看见的列,目前实现有些问题,暂时屏蔽 //使用多选框进行自由列选择,屏蔽不需要看见的列,目前实现有些问题,暂时屏蔽
// 是否展开字段选择 // 是否展开字段选择
// const [showFilter, setShowFilter] = useState(false); // const [showFilter, setShowFilter] = useState(false);
// 是否全选,全选状态相关 // 是否全选,全选状态相关
// const [state, setState] = useState<{ checkedList: [], indeterminate: boolean, checkAll: boolean }>({checkedList: [], indeterminate: true, checkAll: false}); // const [state, setState] = useState<{ checkedList: [], indeterminate: boolean, checkAll: boolean }>({checkedList: [], indeterminate: true, checkAll: false});
// 条件查询时联想输入使用 // 条件查询时联想输入使用
const [options, setOptions] = useState<{whereOption: {}[],orderOption:{}[] }>({whereOption:[],orderOption:[]}); const [options, setOptions] = useState<{ whereOption: {}[], orderOption: {}[] }>({whereOption: [], orderOption: []});
// where输入框内容 // where输入框内容
const [optionInput, setOptionInput] = useState<{whereInput:string,orderInput:string}>({whereInput:"",orderInput:""}); const [optionInput, setOptionInput] = useState<{ whereInput: string, orderInput: string }>({
const [page, setPage] = useState<{ page:number,pageSize:number }>({page:0 ,pageSize:10}); whereInput: "",
orderInput: ""
});
const [page, setPage] = useState<{ page: number, pageSize: number }>({page: 0, pageSize: 10});
// const [defaultInput,setDefaultInput] // const [defaultInput,setDefaultInput]
// 获取数据库数据 // 获取数据库数据
const fetchData = async (whereInput:string,orderInput:string) => { const fetchData = async (whereInput: string, orderInput: string) => {
setLoading(true); setLoading(true);
let temp= {rowData: [], columns: []} let temp = {rowData: [], columns: []}
let option = {where:whereInput, let option = {
order:orderInput,limitStart:"0",limitEnd:"500"} where: whereInput,
order: orderInput, limitStart: "0", limitEnd: "500"
}
await showTableData(dbId, schema, table, option).then(result => { await showTableData(dbId, schema, table, option).then(result => {
if (result.code == 1){ if (result.code == 1) {
setErrMsg({isErr:true,msg:result.datas.error}) setErrMsg({isErr: true, msg: result.datas.error})
}else { } else {
setErrMsg({isErr:false,msg:""}) setErrMsg({isErr: false, msg: ""})
} }
let data = result.datas; let data = result.datas;
setColumns(data.columns) setColumns(data.columns)
...@@ -61,21 +86,21 @@ const fetchData = async (whereInput:string,orderInput:string) => { ...@@ -61,21 +86,21 @@ const fetchData = async (whereInput:string,orderInput:string) => {
}) })
setableData(temp); setableData(temp);
setLoading(false) setLoading(false)
}; };
useEffect(() => { useEffect(() => {
setColumns([]) setColumns([])
setableData({columns: [], rowData: []}) setableData({columns: [], rowData: []})
setErrMsg({isErr:false,msg:""}) setErrMsg({isErr: false, msg: ""})
setOptions({whereOption:[],orderOption:[]}) setOptions({whereOption: [], orderOption: []})
setOptionInput({whereInput:"",orderInput:""}) setOptionInput({whereInput: "", orderInput: ""})
setPage({page:0 ,pageSize:10}) setPage({page: 0, pageSize: 10})
setLoading(false) setLoading(false)
fetchData("",""); fetchData("", "");
}, [dbId, table, schema]); }, [dbId, table, schema]);
//使用多选框进行自由列选择,屏蔽不需要看见的列,目前实现有些问题,暂时屏蔽 //使用多选框进行自由列选择,屏蔽不需要看见的列,目前实现有些问题,暂时屏蔽
// // 单项选择监听 // // 单项选择监听
...@@ -99,8 +124,8 @@ useEffect(() => { ...@@ -99,8 +124,8 @@ useEffect(() => {
// 条件查询时反馈联想信息 // 条件查询时反馈联想信息
const handleRecommend = (value: string) => { const handleRecommend = (value: string) => {
if (columns==null){ if (columns == null) {
return [] return []
} }
let inputSplit: string[] = value.split(" "); let inputSplit: string[] = value.split(" ");
...@@ -110,44 +135,43 @@ const handleRecommend = (value: string) => { ...@@ -110,44 +135,43 @@ const handleRecommend = (value: string) => {
console.log(inputSplit) console.log(inputSplit)
for (let column of columns) { for (let column of columns) {
if (column.startsWith(lastWord)) { if (column.startsWith(lastWord)) {
let msg = inputSplit.join("") + " "+column let msg = inputSplit.join("") + " " + column
recommend.push({value: msg }) recommend.push({value: msg})
} }
} }
return recommend; return recommend;
}; };
const handleWhere = (value:string) =>{ const handleWhere = (value: string) => {
let result = handleRecommend(value) let result = handleRecommend(value)
setOptions({ setOptions({
whereOption:result, whereOption: result,
orderOption:[] orderOption: []
}) })
} }
const handleOrder = (value:string) =>{ const handleOrder = (value: string) => {
let result = handleRecommend(value) let result = handleRecommend(value)
setOptions({ setOptions({
orderOption:result, orderOption: result,
whereOption:[] whereOption: []
}) })
} }
return ( return (
<div> <div>
<Spin spinning={loading} delay={500}> <Spin spinning={loading} delay={500}>
<div className={styles.mrgin_top_40}> <div className={styles.mrgin_top_40}>
{errMsg.isErr?( {errMsg.isErr ? (
<Alert <Alert
message="Error" message="Error"
description={errMsg.msg} description={errMsg.msg}
type="error" type="error"
showIcon showIcon
/> />
):<></>} ) : <></>}
<Row> <Row>
<Col span={12}> <Col span={12}>
<AutoComplete <AutoComplete
...@@ -155,15 +179,19 @@ return ( ...@@ -155,15 +179,19 @@ return (
options={options.whereOption} options={options.whereOption}
style={{width: "100%"}} style={{width: "100%"}}
onSearch={handleWhere} onSearch={handleWhere}
onSelect={(value:string, option)=>{ onSelect={(value: string, option) => {
setOptionInput({whereInput:value, setOptionInput({
orderInput:optionInput.orderInput}) whereInput: value,
orderInput: optionInput.orderInput
})
}} }}
> >
<Input addonBefore="WHERE" placeholder="查询条件" <Input addonBefore="WHERE" placeholder="查询条件"
onChange={(value)=>{ onChange={(value) => {
setOptionInput({whereInput:value.target.value, setOptionInput({
orderInput:optionInput.orderInput}) whereInput: value.target.value,
orderInput: optionInput.orderInput
})
}} }}
/> />
</AutoComplete> </AutoComplete>
...@@ -175,14 +203,18 @@ return ( ...@@ -175,14 +203,18 @@ return (
options={options.orderOption} options={options.orderOption}
style={{width: "100%"}} style={{width: "100%"}}
onSearch={handleOrder} onSearch={handleOrder}
onSelect={(value:string, option)=>{ onSelect={(value: string, option) => {
setOptionInput({whereInput:optionInput.whereInput, setOptionInput({
orderInput:value}) whereInput: optionInput.whereInput,
orderInput: value
})
}} }}
> >
<Input addonBefore="ORDER BY" placeholder="排序" onChange={(value)=>{ <Input addonBefore="ORDER BY" placeholder="排序" onChange={(value) => {
setOptionInput({whereInput:optionInput.whereInput, setOptionInput({
orderInput:value.target.value}) whereInput: optionInput.whereInput,
orderInput: value.target.value
})
}}/> }}/>
</AutoComplete> </AutoComplete>
</Col> </Col>
...@@ -216,8 +248,8 @@ return ( ...@@ -216,8 +248,8 @@ return (
{/*</Col>*/} {/*</Col>*/}
<Col span={1}> <Col span={1}>
<Tooltip title="查询"> <Tooltip title="查询">
<Button type="primary" shape="circle" icon={<SearchOutlined/>} size="middle" onClick={(event)=>{ <Button type="primary" shape="circle" icon={<SearchOutlined/>} size="middle" onClick={(event) => {
fetchData(optionInput.whereInput,optionInput.orderInput) fetchData(optionInput.whereInput, optionInput.orderInput)
}}/> }}/>
</Tooltip> </Tooltip>
</Col> </Col>
...@@ -231,10 +263,12 @@ return ( ...@@ -231,10 +263,12 @@ return (
<Table style={{height: '95vh'}} <Table style={{height: '95vh'}}
columns={tableData.columns} columns={tableData.columns}
dataSource={tableData.rowData} dataSource={tableData.rowData}
pagination={{pageSize:page.pageSize, pagination={{
pageSize: page.pageSize,
onChange: (pageNum, pageSize) => { onChange: (pageNum, pageSize) => {
setPage({page:pageNum,pageSize:pageSize}); setPage({page: pageNum, pageSize: pageSize});
}}} }
}}
scroll={{y: "80vh", x: true}} scroll={{y: "80vh", x: true}}
/> />
</div> </div>
...@@ -242,7 +276,7 @@ return ( ...@@ -242,7 +276,7 @@ return (
</div> </div>
) )
}; };
export default TableData export default TableData
/*
*
* 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.
*
*/
//主体样式
.container { .container {
margin-top: 5px;
background: #ffffff; background: #ffffff;
height: 95vh; height: 95vh;
padding: 8px padding: 8px
} }
//顶部数据库列表父组件样式,覆盖原有seagement样式
.headerBarContent {
overflow-x: scroll;
width: 100%;
background-color:#fafafa;
:global{
.ant-segmented:not(.ant-segmented-disabled):hover, .ant-segmented:not(.ant-segmented-disabled):focus{
background-color:#fafafa;
}
}
}
//顶部数据库列表样式
.headerBar {
background: #fafafa;
padding: 8px;
}
//数据库列表单条car样式
.headerCard {
width:200px;
:global{
.ant-card-body{
padding: 8px;
}
}
}
//table标题样式
.tableListHead{
background-color: #f9f9f9;
padding: 8px;
:global{
.ant-card-meta-title{
font-size: 14px;
}
.ant-card-meta-description{
color: rgba(0, 0, 0, 0.45);
font-size: 10px;
.content-height{ }
height: 100%; }
} }
import { PageContainer } from '@ant-design/pro-layout'; // /*
*
* 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 {PageContainer} from '@ant-design/pro-layout'; //
import styles from './index.less'; import styles from './index.less';
import { Row, Col, Tabs, Select, Tag, Empty, Tree, Spin } from 'antd'; import {Row, Col, Tabs, Tag, Empty, Tree, Segmented, Card, Image, Spin, Button} from 'antd';
import React, { Key, useEffect, useState } from 'react'; import React, {Key, useEffect, useState} from 'react';
import { showMetaDataTable } from '@/components/Studio/StudioEvent/DDL'; import {clearMetaDataTable, showMetaDataTable} from '@/components/Studio/StudioEvent/DDL';
import { Scrollbars } from 'react-custom-scrollbars'; import {getData} from '@/components/Common/crud';
import { getData } from '@/components/Common/crud';
import { import {
BarsOutlined, BarsOutlined, CheckCircleOutlined,
ConsoleSqlOutlined, ConsoleSqlOutlined,
DatabaseOutlined, DatabaseOutlined,
DownOutlined, DownOutlined, ExclamationCircleOutlined,
ReadOutlined, ReadOutlined,
TableOutlined, TableOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { TreeDataNode } from '@/components/Studio/StudioTree/Function'; import {TreeDataNode} from '@/components/Studio/StudioTree/Function';
import Tables from '@/pages/DataBase/Tables'; import Tables from '@/pages/DataBase/Tables';
import Columns from '@/pages/DataBase/Columns'; import Columns from '@/pages/DataBase/Columns';
import Divider from 'antd/es/divider'; import Divider from 'antd/es/divider';
import Generation from '@/pages/DataBase/Generation'; import Generation from '@/pages/DataBase/Generation';
import TableData from '@/pages/DataCenter/MetaData/TableData'; import TableData from '@/pages/DataCenter/MetaData/TableData';
const { DirectoryTree } = Tree; import {FALLBACK, getDBImage} from "@/pages/DataBase/DB";
const { TabPane } = Tabs; import Meta from "antd/lib/card/Meta";
const {DirectoryTree} = Tree;
const {TabPane} = Tabs;
const Container: React.FC<{}> = (props: any) => { const Container: React.FC<{}> = (props: any) => {
// const { dispatch} = props;
let [database, setDatabase] = useState([
{ let [database, setDatabase] = useState<[{
id: '', id: number,
name: string,
alias: string,
type: string,
enabled: string,
groupName: string,
status: string,
time: string
}]>([{
id: -1,
name: '', name: '',
alias: '', alias: '',
type: '', type: '',
enabled: '', enabled: '',
}, groupName: '',
]); status: '',
time:''
}]);
const [databaseId, setDatabaseId] = useState<number>(); const [databaseId, setDatabaseId] = useState<number>();
const [treeData, setTreeData] = useState<[]>([]); const [treeData, setTreeData] = useState<{tables:[],updateTime:string}>({tables:[],updateTime:"none"});
const [row, setRow] = useState<TreeDataNode>(); const [row, setRow] = useState<TreeDataNode>();
const [loadingDatabase, setloadingDatabase] = useState(false); const [loadingDatabase, setloadingDatabase] = useState(false);
...@@ -58,22 +93,22 @@ const Container: React.FC<{}> = (props: any) => { ...@@ -58,22 +93,22 @@ const Container: React.FC<{}> = (props: any) => {
for (let i = 0; i < tables.length; i++) { for (let i = 0; i < tables.length; i++) {
tables[i].title = tables[i].name; tables[i].title = tables[i].name;
tables[i].key = tables[i].name; tables[i].key = tables[i].name;
tables[i].icon = <DatabaseOutlined />; tables[i].icon = <DatabaseOutlined/>;
tables[i].children = tables[i].tables; tables[i].children = tables[i].tables;
for (let j = 0; j < tables[i].children.length; j++) { for (let j = 0; j < tables[i].children.length; j++) {
tables[i].children[j].title = tables[i].children[j].name; tables[i].children[j].title = tables[i].children[j].name;
tables[i].children[j].key = tables[i].name + '.' + tables[i].children[j].name; tables[i].children[j].key = tables[i].name + '.' + tables[i].children[j].name;
tables[i].children[j].icon = <TableOutlined />; tables[i].children[j].icon = <TableOutlined/>;
tables[i].children[j].isLeaf = true; tables[i].children[j].isLeaf = true;
tables[i].children[j].schema = tables[i].name; tables[i].children[j].schema = tables[i].name;
tables[i].children[j].table = tables[i].children[j].name; tables[i].children[j].table = tables[i].children[j].name;
} }
} }
setTreeData(tables); setTreeData({tables:tables,updateTime:result.time});
} else { } else {
setTreeData([]); setTreeData({tables:[],updateTime:"none"});
} }
}); });
setloadingDatabase(false); setloadingDatabase(false);
...@@ -83,31 +118,16 @@ const Container: React.FC<{}> = (props: any) => { ...@@ -83,31 +118,16 @@ const Container: React.FC<{}> = (props: any) => {
fetchDatabaseList(); fetchDatabaseList();
}, []); }, []);
const getDataBaseOptions = () => { const onChangeDataBase = (value: string|number) => {
return ( onRefreshTreeData(Number(value));
<> setRow(null);
{database.map(({ id, name, alias, type, enabled }) => (
<Select.Option
key={id}
value={id}
label={
<>
<Tag color={enabled ? 'processing' : 'error'}>{type}</Tag>
{alias === '' ? name : alias}
</>
}
>
<Tag color={enabled ? 'processing' : 'error'}>{type}</Tag>
{alias === '' ? name : alias}
</Select.Option>
))}
</>
);
}; };
const onChangeDataBase = (value: number) => { const refeshDataBase = (value: string | number) => {
onRefreshTreeData(value); setloadingDatabase(true);
setRow(null); clearMetaDataTable(Number(databaseId)).then(result=>{
onChangeDataBase(Number(value));
})
}; };
const showTableInfo = (selected: boolean, node: TreeDataNode) => { const showTableInfo = (selected: boolean, node: TreeDataNode) => {
...@@ -121,44 +141,107 @@ const Container: React.FC<{}> = (props: any) => { ...@@ -121,44 +141,107 @@ const Container: React.FC<{}> = (props: any) => {
fetchDatabase(databaseId); fetchDatabase(databaseId);
}; };
const buildDatabaseBar = () => {
return database.map((item) => {
return {
label: (
<Card className={styles.headerCard}
hoverable={false} bordered={false}>
<Row>
<Col span={11}>
<Image style={{float: "left", paddingRight: "10px"}}
height={50}
preview={false}
src={getDBImage(item.type)}
fallback={FALLBACK}
/>
</Col>
<Col span={11}>
<div>
<p>{item.alias}</p>
<Tag color="blue" key={item.groupName}>
{item.groupName}
</Tag>
{(item.status) ?
(<Tag icon={<CheckCircleOutlined/>} color="success">
正常
</Tag>) :
<Tag icon={<ExclamationCircleOutlined/>} color="warning">
异常
</Tag>}
</div>
</Col>
</Row>
</Card>
),
value: item.id,
}
}
)
};
const buildListTitle = () => {
for (let item of database) {
if (item.id == databaseId) {
return (
<div>
<div style={{position: "absolute", right: "10px"}}>
<Button type="link" size="small"
loading={loadingDatabase}
onClick={()=>refeshDataBase(databaseId)}
>刷新</Button>
</div>
<div>{item.alias}</div>
</div>
)
}
}
return (<div>未选择数据库</div>)
}
return ( return (
<div className={styles.container}>
<div> <div>
<> <div className={styles.headerBarContent}>
<Segmented className={styles.headerBar}
options={buildDatabaseBar()}
onChange={onChangeDataBase}
/>
</div>
<div className={styles.container}>
<Row gutter={24}> <Row gutter={24}>
<Col span={4}> <Col span={4}>
<Select
style={{
width: '90%',
}}
placeholder="选择数据源"
optionLabelProp="label"
onChange={onChangeDataBase}
>
{getDataBaseOptions()}
</Select>
<Spin spinning={loadingDatabase} delay={500}> <Spin spinning={loadingDatabase} delay={500}>
<Scrollbars <Card
style={{ type="inner"
height: '90vh', bodyStyle={{padding: 0}}
}}
> >
{treeData.length > 0 ? ( <Meta title={buildListTitle()}
className={styles.tableListHead}
description={"上次更新:"+treeData.updateTime}
/>
{treeData.tables.length > 0 ? (
<DirectoryTree <DirectoryTree
height={850}
showIcon showIcon
switcherIcon={<DownOutlined />} switcherIcon={<DownOutlined/>}
treeData={treeData} treeData={treeData.tables}
onSelect={( onSelect={(
selectedKeys: Key[], selectedKeys: Key[],
{ event, selected, node, selectedNodes, nativeEvent } {event, selected, node, selectedNodes, nativeEvent}
) => { ) => {
showTableInfo(selected, node); showTableInfo(selected, node);
}} }}
/> />
) : ( ) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
)} )}
</Scrollbars> </Card>
</Spin> </Spin>
</Col> </Col>
...@@ -169,7 +252,7 @@ const Container: React.FC<{}> = (props: any) => { ...@@ -169,7 +252,7 @@ const Container: React.FC<{}> = (props: any) => {
<TabPane <TabPane
tab={ tab={
<span> <span>
<ReadOutlined /> <ReadOutlined/>
描述 描述
</span> </span>
} }
...@@ -179,49 +262,49 @@ const Container: React.FC<{}> = (props: any) => { ...@@ -179,49 +262,49 @@ const Container: React.FC<{}> = (props: any) => {
表信息 表信息
</Divider> </Divider>
{row ? ( {row ? (
<Tables table={row} /> <Tables table={row}/>
) : ( ) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
)} )}
<Divider orientation="left" plain> <Divider orientation="left" plain>
字段信息 字段信息
</Divider> </Divider>
{row ? ( {row ? (
<Columns dbId={databaseId} schema={row.schema} table={row.table} /> <Columns dbId={databaseId} schema={row.schema} table={row.table}/>
) : ( ) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
)} )}
</TabPane> </TabPane>
<TabPane <TabPane
tab={ tab={
<span> <span>
<BarsOutlined /> <BarsOutlined/>
数据查询 数据查询
</span> </span>
} }
key="exampleData" key="exampleData"
> >
{row ? ( {row ? (
<TableData dbId={databaseId} schema={row.schema} table={row.table} rows={row.rows}/> <TableData dbId={databaseId} schema={row.schema} table={row.table} />
) : ( ) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
)} )}
</TabPane> </TabPane>
<TabPane <TabPane
tab={ tab={
<span> <span>
<ConsoleSqlOutlined /> <ConsoleSqlOutlined/>
SQL 生成 SQL 生成
</span> </span>
} }
key="sqlGeneration" key="sqlGeneration"
> >
{row ? ( {row ? (
<Generation dbId={databaseId} schema={row.schema} table={row.table} /> <Generation dbId={databaseId} schema={row.schema} table={row.table}/>
) : ( ) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
)} )}
</TabPane> </TabPane>
...@@ -230,7 +313,6 @@ const Container: React.FC<{}> = (props: any) => { ...@@ -230,7 +313,6 @@ const Container: React.FC<{}> = (props: any) => {
</div> </div>
</Col> </Col>
</Row> </Row>
</>
</div> </div>
</div> </div>
); );
...@@ -239,7 +321,7 @@ const Container: React.FC<{}> = (props: any) => { ...@@ -239,7 +321,7 @@ const Container: React.FC<{}> = (props: any) => {
export default () => { export default () => {
return ( return (
<PageContainer> <PageContainer>
<Container /> <Container/>
</PageContainer> </PageContainer>
); );
}; };
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