Skip to content

Commit

Permalink
fix: query finish order
Browse files Browse the repository at this point in the history
  • Loading branch information
invm authored and Michael Ionov committed Dec 22, 2023
1 parent c10376c commit 2795c47
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 79 deletions.
2 changes: 1 addition & 1 deletion src-tauri/src/handlers/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub async fn enqueue_query(
conn_id,
tab_idx,
status: QueryTaskStatus::Progress,
results_sets: statements.iter().map(|s| s.1.clone()).collect(),
result_sets: statements.iter().map(|s| s.1.clone()).collect(),
});
}
if statements.is_empty() {
Expand Down
5 changes: 3 additions & 2 deletions src-tauri/src/queues/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub struct QueryTaskEnqueueResult {
pub conn_id: String,
pub tab_idx: usize,
pub status: QueryTaskStatus,
pub results_sets: Vec<String>,
pub result_sets: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand All @@ -89,7 +89,8 @@ pub async fn async_process_model(
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
while let Some(input) = input_rx.recv().await {
let task = input;
// tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
// so what happened is that this ran too fast and the UI didn't have time to update, a single millisecond is enough
tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;
match task.conn.execute_query(&task.query).await {
Ok(result_set) => match write_query(&task.id, &result_set) {
Ok(path) => {
Expand Down
20 changes: 7 additions & 13 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,14 @@ function App() {
const compareAndAssign = async (event: QueryTaskResult) => {
// TODO: this does not take into account the connection, when we have multiple connections
// FIXME: Why more than 3 queries in a tab suddenly breaks?
if (getConnection().id === event.conn_id && idx === event.tab_idx) {
if (event.status === 'Completed') {
const { status, query_idx, tab_idx, conn_id } = event;
if (getConnection().id === conn_id && idx === tab_idx) {
if (status === 'Completed') {
const md = await getQueryMetadata(event.path);
const metadata = {
...md,
path: event.path,
status: event.status,
};
updateResultSet(event.tab_idx, event.query_idx, metadata);
} else if (event.status === 'Error') {
updateResultSet(event.tab_idx, event.query_idx, {
status: event.status,
error: event.error,
});
const metadata = { ...md, path: event.path, status };
updateResultSet(tab_idx, query_idx, metadata);
} else if (status === 'Error') {
updateResultSet(tab_idx, query_idx, { status, error: event.error });
}
}
};
Expand Down
13 changes: 11 additions & 2 deletions src/components/Screens/Console/Content/QueryTab/QueryTextArea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export const QueryTextArea = () => {
updateContentTab('error', undefined);
const activeConnection = getConnection();
try {
const { results_sets } = await invoke<QueryTaskEnqueueResult>(
const { result_sets } = await invoke<QueryTaskEnqueueResult>(
'enqueue_query',
{
connId: activeConnection.id,
Expand All @@ -111,7 +111,7 @@ export const QueryTextArea = () => {
);
updateContentTab('data', {
query: code(),
result_sets: results_sets.map((id) => ({
result_sets: result_sets.map((id) => ({
id,
})),
});
Expand Down Expand Up @@ -143,10 +143,19 @@ export const QueryTextArea = () => {
createShortcut(['Control', 'l'], () => setFocused(true));
createShortcut(['Control', 'Shift', 'F'], onFormat);

const onTestClick = () => {
console.log(getContentData('Query'));
}

return (
<div class="flex-1 flex flex-col">
<div class="w-full px-2 py-1 bg-base-100 border-b-2 border-accent flex justify-between items-center">
<div class="flex items-center">
<ActionRowButton
dataTip={'Testing'}
onClick={onTestClick}
icon={<EditIcon />}
/>
<ActionRowButton
dataTip={t('console.actions.format')}
onClick={onFormat}
Expand Down
15 changes: 5 additions & 10 deletions src/components/Screens/Console/Content/QueryTab/ResultesTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,19 @@ import { dracula } from '@uiw/codemirror-theme-dracula';
import { search } from '@codemirror/search';
import { basicSetup, EditorView } from 'codemirror';
import { json } from '@codemirror/lang-json';
import {
createCodeMirror,
createEditorControlledValue,
} from 'solid-codemirror';
import { createCodeMirror, createEditorControlledValue } from 'solid-codemirror';
import { Pagination } from './components/Pagination';
import { useAppSelector } from 'services/Context';
import { Row } from 'interfaces';

type TableColumn = { title: string; field: string; resizeable: boolean };

const parseObjRecursive = (
obj: unknown
): Record<string, unknown | unknown[]> | null | unknown => {
const parseObjRecursive = (obj: unknown): Record<string, unknown | unknown[]> | null | unknown => {
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
return obj.map(parseObjRecursive);
} else if (obj !== null) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => [k, parseObjRecursive(v)])
);
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, parseObjRecursive(v)]));
} else {
return obj;
}
Expand Down Expand Up @@ -58,6 +51,8 @@ export const ResultsTable = () => {

const updateRows = async () => {
const result_set = getContentData('Query').result_sets[queryIdx()];
// console.log(getContentData('Query').result_sets)
// console.log({ result_set });
if (result_set?.status !== 'Completed') {
setRows([]);
return;
Expand Down
4 changes: 2 additions & 2 deletions src/components/Screens/Console/Sidebar/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const Sidebar = () => {
connId: config.id,
});
const schema = columnsToSchema(result, config.dialect);
updateConnectionTab("schema", { schema });
updateConnectionTab("schema", schema);

const procedures = await invoke<RawQueryResult>("get_procedures", {
connId: getConnection().id,
Expand All @@ -65,7 +65,7 @@ export const Sidebar = () => {
onChange={(e) => select(e.currentTarget.value)}
class="select select-accent select-bordered select-xs w-full"
>
<For each={Object.keys(getConnection().schema)}>
<For each={(getConnection() && Object.keys(getConnection()?.schema)) ?? []}>
{(_schema) => (
<option class="py-1" value={_schema}>
{_schema}
Expand Down
2 changes: 1 addition & 1 deletion src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export type QueryTaskEnqueueResult = {
conn_id: string;
tab_id: string;
status: QueryTaskStatusType;
results_sets: string[];
result_sets: string[];
};

export type QueryTaskResult = {
Expand Down
71 changes: 23 additions & 48 deletions src/services/Connections.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
import { createStore, produce } from 'solid-js/store';
import {
Column,
ConnectionConfig,
ResultSet,
Row,
Table,
TableEntity,
} from '../interfaces';
import { Column, ConnectionConfig, ResultSet, Row, Table, TableEntity } from '../interfaces';
import { Store } from 'tauri-plugin-store-api';
import { debounce, firstKey } from 'utils/utils';
import { invoke } from '@tauri-apps/api';
Expand Down Expand Up @@ -35,11 +28,7 @@ type ContentTabData = {
[ContentTab.TableStructure]: TableStructureContentTabData;
};

export const newContentTab = <T extends ContentComponentKeys>(
label: string,
key: T,
data?: ContentTabData[T]
) => {
export const newContentTab = <T extends ContentComponentKeys>(label: string, key: T, data?: ContentTabData[T]) => {
switch (key) {
case ContentTab.Query:
return {
Expand Down Expand Up @@ -158,23 +147,20 @@ export const ConnectionsService = () => {
},
Promise.resolve([] as ConnectionTab[])
);
setConnectionStore(() => ({ ...conn_tabs, tabs }));
const content = await getSavedData(CONTENT_KEY);
setContentStore(() => content as ContentStore);
if (tabs.length) {
setConnectionStore(() => ({ ...conn_tabs, tabs }));
const content = await getSavedData(CONTENT_KEY);
setContentStore(() => content as ContentStore);
}
updateStore();
};

const updateStore = debounce(async () => {
await store.set(CONNECTIONS_KEY, JSON.stringify(connectionStore));
const tabs = contentStore.tabs.map((t) =>
t.key === ContentTab.Query
? { ...t, data: { ...t.data, result_sets: [] } }
: t
);
await store.set(
CONTENT_KEY,
JSON.stringify({ idx: contentStore.idx, tabs })
t.key === ContentTab.Query ? { ...t, data: { ...t.data, result_sets: [] } } : t
);
await store.set(CONTENT_KEY, JSON.stringify({ idx: contentStore.idx, tabs }));
await store.save();
}, INTERVAL);

Expand All @@ -192,11 +178,11 @@ export const ConnectionsService = () => {
};

const removeConnectionTab = async (id: string) => {
setConnectionStore('idx', 0);
setConnectionStore(
'tabs',
connectionStore.tabs.filter((t) => t.id !== id)
);
setConnectionStore('idx', 0);
updateStore();
};

Expand All @@ -208,6 +194,10 @@ export const ConnectionsService = () => {
return connectionStore.tabs[connectionStore.idx - 1];
};

const getSchema = (schema: string) => {
return (getConnection() && getConnection().schema[schema]) ?? {};
};

const getContent = () => contentStore.tabs[contentStore.idx];

const getContentData = <T extends keyof ContentTabData>(_key: T) => {
Expand Down Expand Up @@ -248,52 +238,36 @@ export const ConnectionsService = () => {
}
};

const updateConnectionTab = <T extends keyof ConnectionTab>(
key: T,
data: ConnectionTab[T],
idx?: number
) => {
const updateConnectionTab = <T extends keyof ConnectionTab>(key: T, data: ConnectionTab[T], idx?: number) => {
const tab = getConnection();
if (!tab) return;
setConnectionStore('tabs', idx ?? connectionStore.idx - 1, key, data);
updateStore();
};

const updateContentTab = <T extends keyof ContentTab>(
key: T,
data: ContentTab[T],
idx?: number
) => {
const updateContentTab = <T extends keyof ContentTab>(key: T, data: ContentTab[T], idx?: number) => {
const tab = getContent();
console.log('updateContentTab ', data)
if (!tab) return;
setContentStore('tabs', idx ?? contentStore.idx, key, data);
updateStore();
};

const updateResultSet = (
tab_idx: number,
query_idx: number,
data: Partial<ResultSet>
) => {
const updateResultSet = (tab_idx: number, query_idx: number, data: Partial<ResultSet>) => {
console.log({ query_idx, data });
setContentStore('tabs', tab_idx, 'data', (d) => ({
...d,
result_sets: (d as QueryContentTabData).result_sets.map((r, i) =>
i === query_idx ? { ...r, ...data } : r
),
result_sets: (d as QueryContentTabData).result_sets.map((r, i) => (i === query_idx ? { ...r, ...data } : r)),
}));
console.log({ contentStore });
};

const getSchemaTables = (sch = connectionStore.schema): Table[] => {
const _tables = Object.entries(getConnection().schema[sch]).reduce(
const _tables = Object.entries(getSchema(sch)).reduce(
(acc: Table[], [name, columns]) => [
...acc,
{
name,
columns: Object.entries(columns).reduce(
(cols: Column[], [name, props]) => [...cols, { name, props }],
[]
),
columns: Object.entries(columns).reduce((cols: Column[], [name, props]) => [...cols, { name, props }], []),
},
],
[]
Expand Down Expand Up @@ -336,5 +310,6 @@ export const ConnectionsService = () => {
selectNextQuery,
queryIdx,
updateResultSet,
getSchema,
};
};

0 comments on commit 2795c47

Please sign in to comment.