Skip to content

Commit

Permalink
【Fixed】console save bug
Browse files Browse the repository at this point in the history
  • Loading branch information
shanhexi committed Oct 31, 2023
1 parent 22e8456 commit 6e12b2a
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 57 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"pgsql",
"pnpm",
"Popconfirm",
"quickinput",
"redownload",
"remaininguses",
"RESTAI",
Expand Down
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
**Changelog**
- ⭐【New Features】Query results can be refreshed
- ⚡️【Optimize】Console Tabs adaptive width
- 🐞【Fixed】
- 🐞【Fixed】console save bug

**更新日志**
- ⭐【新功能】查询结果支持刷新
- ⚡️【优化】控制台Tabs自适应宽度
- 🐞【修复】
- 🐞【修复】console保存bug


# 3.0.5
Expand Down
11 changes: 6 additions & 5 deletions chat2db-client/src/blocks/SQLExecute/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React, { memo, useRef, useState } from 'react';
import React, { memo, useRef } from 'react';
import { connect } from 'umi';
import styles from './index.less';
import classnames from 'classnames';
import DraggableContainer from '@/components/DraggableContainer';
import Console, { IAppendValue } from '@/components/Console';
import Console, { IConsoleRef } from '@/components/Console';
import SearchResult, { ISearchResultRef } from '@/components/SearchResult';
import { DatabaseTypeCode, ConsoleStatus } from '@/constants';
import { IWorkspaceModelState, IWorkspaceModelType } from '@/models/workspace';
Expand All @@ -23,16 +23,17 @@ interface IProps {
consoleId: number;
consoleName: string;
initDDL: string;
status?: ConsoleStatus;
};
}

const SQLExecute = memo<IProps>((props) => {
const { data, workspaceModel, aiModel, isActive, dispatch } = props;
const draggableRef = useRef<any>();
const [appendValue, setAppendValue] = useState<IAppendValue>();
const { curTableList, curWorkspaceParams } = workspaceModel;
// const [sql, setSql] = useState<string>('');
const searchResultRef = useRef<ISearchResultRef>(null);
const consoleRef = useRef<IConsoleRef>(null);

// useEffect(() => {
// if (!doubleClickTreeNodeData) {
Expand All @@ -53,18 +54,18 @@ const SQLExecute = memo<IProps>((props) => {
// }, [doubleClickTreeNodeData]);

useUpdateEffect(() => {
setAppendValue({ text: data.initDDL });
consoleRef.current?.editorRef?.setValue(data.initDDL, 'cover');
}, [data.initDDL]);

return (
<div className={classnames(styles.box)}>
<DraggableContainer layout="column" className={styles.boxRightCenter}>
<div ref={draggableRef} className={styles.boxRightConsole}>
<Console
ref={consoleRef}
source="workspace"
defaultValue={data.initDDL}
isActive={isActive}
appendValue={appendValue}
executeParams={{ ...data }}
hasAiChat={true}
hasAi2Lang={true}
Expand Down
122 changes: 78 additions & 44 deletions chat2db-client/src/components/Console/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ function Console(props: IProps, ref: ForwardedRef<IConsoleRef>) {
const closeEventSource = useRef<any>();
// 上一次同步的console数据
const lastSyncConsole = useRef<any>(defaultValue);
const [saveStatus, setSaveStatus] = useState<ConsoleStatus>(executeParams.status || ConsoleStatus.DRAFT);

/**
* 当前选择的AI类型是Chat2DBAI
Expand All @@ -131,70 +132,91 @@ function Console(props: IProps, ref: ForwardedRef<IConsoleRef>) {
}
}, [appendValue]);

useImperativeHandle(ref, () => ({
editorRef: editorRef?.current,
}));
useImperativeHandle(
ref,
() => ({
editorRef: editorRef?.current,
}),
[editorRef?.current],
);

useEffect(() => {
if (source !== 'workspace') {
return;
}
// 离开时保存
if (!isActive && timerRef.current) {
if (!isActive) {
// 离开时清除定时器
indexedDB.updateData('chat2db', 'workspaceConsoleDDL', {
consoleId: executeParams.consoleId!,
ddl: editorRef?.current?.getAllContent(),
userId: getCookie('CHAT2DB.USER_ID'),
});
clearInterval(timerRef.current);
if (timerRef.current) {
clearInterval(timerRef.current);
}
const curValue = editorRef?.current?.getAllContent();
if (curValue === lastSyncConsole.current) {
return;
}
if (saveStatus === ConsoleStatus.RELEASE) {
saveConsole(curValue, true);
} else {
indexedDB
.updateData('chat2db', 'workspaceConsoleDDL', {
consoleId: executeParams.consoleId!,
ddl: curValue,
userId: getCookie('CHAT2DB.USER_ID'),
})
.then(() => {
lastSyncConsole.current = curValue;
});
}
} else {
timingAutoSave();
}
return () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
}, [isActive]);

useEffect(() => {
if (saveStatus === ConsoleStatus.RELEASE) {
editorRef?.current?.setValue(defaultValue, 'cover');
} else {
// 活跃时自动保存
indexedDB
.getDataByCursor('chat2db', 'workspaceConsoleDDL', {
consoleId: executeParams.consoleId!,
userId: getCookie('CHAT2DB.USER_ID'),
})
.then((res: any) => {
const value = defaultValue || res?.[0]?.ddl || '';
// oldValue是为了处理函数视图等,他们是带着值来的,不需要去数据库取值
const oldValue = editorRef?.current?.getAllContent();
if (value !== oldValue) {
editorRef?.current?.setValue(value, 'reset');
if (!oldValue) {
editorRef?.current?.setValue(res?.[0]?.ddl || '', 'cover');
}
setTimeout(() => {
timingAutoSave();
}, 0);
});
}
return () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
}, [isActive]);
}, []);

function timingAutoSave(status?: ConsoleStatus) {
function timingAutoSave(_status?: ConsoleStatus) {
if (timerRef.current) {
clearInterval(timerRef.current);
}
timerRef.current = setInterval(() => {
const ddl = editorRef?.current?.getAllContent();
if (ddl === lastSyncConsole.current) {
const curValue = editorRef?.current?.getAllContent();
if (curValue === lastSyncConsole.current) {
return;
}
lastSyncConsole.current = ddl;
if (executeParams.status === ConsoleStatus.RELEASE || status === ConsoleStatus.RELEASE) {
const p: any = {
id: executeParams.consoleId,
ddl,
};
historyServer.updateSavedConsole(p);
if (saveStatus === ConsoleStatus.RELEASE || _status === ConsoleStatus.RELEASE) {
saveConsole(curValue, true);
} else {
indexedDB.updateData('chat2db', 'workspaceConsoleDDL', {
consoleId: executeParams.consoleId!,
ddl,
userId: getCookie('CHAT2DB.USER_ID'),
});
indexedDB
.updateData('chat2db', 'workspaceConsoleDDL', {
consoleId: executeParams.consoleId!,
ddl: curValue,
userId: getCookie('CHAT2DB.USER_ID'),
})
.then(() => {
lastSyncConsole.current = curValue;
});
}
}, 5000);
}
Expand Down Expand Up @@ -384,8 +406,7 @@ function Console(props: IProps, ref: ForwardedRef<IConsoleRef>) {
props.onExecuteSQL && props.onExecuteSQL(sqlContent);
};

const saveConsole = (value?: string) => {
// const a = editorRef.current?.getAllContent();
const saveConsole = (value?: string, noPrompting?: boolean) => {
const p: any = {
id: executeParams.consoleId,
status: ConsoleStatus.RELEASE,
Expand All @@ -394,6 +415,11 @@ function Console(props: IProps, ref: ForwardedRef<IConsoleRef>) {

historyServer.updateSavedConsole(p).then(() => {
indexedDB.deleteData('chat2db', 'workspaceConsoleDDL', executeParams.consoleId!);
lastSyncConsole.current = value;
setSaveStatus(ConsoleStatus.RELEASE);
if (noPrompting) {
return;
}
message.success(i18n('common.tips.saveSuccessfully'));
props.onConsoleSave && props.onConsoleSave();
timingAutoSave(ConsoleStatus.RELEASE);
Expand Down Expand Up @@ -570,8 +596,16 @@ function Console(props: IProps, ref: ForwardedRef<IConsoleRef>) {
);
}

const dvaModel = connect(({ ai, loading }: { ai: IAIState; loading: any }) => ({
aiModel: ai,
remainingBtnLoading: loading.effects['ai/fetchRemainingUse'],
}));
const dvaModel = connect(
({ ai, loading }: { ai: IAIState; loading: any }) => {
return {
aiModel: ai,
remainingBtnLoading: loading.effects['ai/fetchRemainingUse'],
};
},
null,
null,
{ forwardRef: true },
);

export default dvaModel(forwardRef(Console));
4 changes: 1 addition & 3 deletions chat2db-client/src/pages/demo/index.less
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
.page {
> div {
margin-bottom: 30px;
}
height: 500px;
}
40 changes: 38 additions & 2 deletions chat2db-client/src/pages/demo/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import React, { useEffect, useState } from 'react';
import styles from './index.less';
import MonacoEditor from '@/components/Console/MonacoEditor';
import { Tabs } from 'antd';

export enum CustomerTypeEnum {
visitor = 'visitor',
Expand All @@ -10,13 +13,46 @@ export enum CustomerTypeEnum2 {
person = 'person',
}

const list = [
"select if((`performance_schema`.`accounts`.`HOST` is null),'background',`performance_schema`.`accounts`.`HOST`) AS `host`,sum(`sys`.`stmt`.`total`) AS `statements`,format_pico_time(sum(`sys`.`stmt`.`total_latency`)) AS `statement_latency`,format_pico_time(ifnull((sum(`sys`.`stmt`.`total_latency`) / nullif(sum(`sys`.`stmt`.`total`),0)),0)) AS `statement_avg_latency`,sum(`sys`.`stmt`.`full_scans`) AS `table_scans`,sum(`sys`.`io`.`ios`) AS `file_ios`,format_pico_time(sum(`sys`.`io`.`io_latency`)) AS `file_io_latency`,sum(`performance_schema`.`accounts`.`CURRENT_CONNECTIONS`) AS `current_connections`,sum(`performance_schema`.`accounts`.`TOTAL_CONNECTIONS`) AS `total_connections`,count(distinct `performance_schema`.`accounts`.`USER`) AS `unique_users`,format_bytes(sum(`sys`.`mem`.`current_allocated`)) AS `current_memory`,format_bytes(sum(`sys`.`mem`.`total_allocated`)) AS `total_memory_allocated` from (((`performance_schema`.`accounts` join `sys`.`x$host_summary_by_statement_latency` `stmt` on((`performance_schema`.`accounts`.`HOST` = `sys`.`stmt`.`host`))) join `sys`.`x$host_summary_by_file_io` `io` on((`performance_schema`.`accounts`.`HOST` = `sys`.`io`.`host`))) join `sys`.`x$memory_by_host_by_current_bytes` `mem` on((`performance_schema`.`accounts`.`HOST` = `sys`.`mem`.`host`))) group by if((`performance_schema`.`accounts`.`HOST` is null),'background',`performance_schema`.`accounts`.`HOST`)",
'Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!Bug: chatglm3 不支持!',
'建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名建议: 鼠标移上去显示表全名,目前表名太长,看不全表名',
];

export type CustomerType1 = CustomerTypeEnum | CustomerTypeEnum2;

const App: React.FC = () => {

const items = [
{
key: '1',
label: 'Tab 1',
forceRender: true,
children:<div className={styles.page}>
<MonacoEditor id="001" defaultValue={list[0]} />
</div>
},
{
key: '2',
label: 'Tab 2',
forceRender: true,
children: <div className={styles.page}>
<MonacoEditor id="002" defaultValue={list[1]} />
</div>
},
{
key: '3',
label: 'Tab 3',
forceRender: true,
children:
<div className={styles.page}>
<MonacoEditor id="003" defaultValue={list[2]} />
</div>
},
];

return (
<div>demo</div>

<Tabs items={items} />
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,6 @@ const WorkspaceRight = memo<IProps>((props: IProps) => {
activeKey={activeConsoleId}
editableNameOnBlur={editableNameOnBlur}
items={tabsList}
// lastTabCannotClosed
/>
</div>
{/* <WorkspaceExtend className={styles.workspaceExtend} /> */}
Expand Down

0 comments on commit 6e12b2a

Please sign in to comment.