From a76f5cdbf20db665cb7de3f065da83019959b984 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Tue, 5 Mar 2024 21:31:33 +0100 Subject: [PATCH] avoid connecting twice --- src/renderer/component/Connection/ConnectionStack.tsx | 10 ++++++++-- src/renderer/utils/error.tsx | 11 +++++++++++ src/sql/index.ts | 9 ++++++++- 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 src/renderer/utils/error.tsx diff --git a/src/renderer/component/Connection/ConnectionStack.tsx b/src/renderer/component/Connection/ConnectionStack.tsx index 94fb500..a5d62d9 100644 --- a/src/renderer/component/Connection/ConnectionStack.tsx +++ b/src/renderer/component/Connection/ConnectionStack.tsx @@ -10,6 +10,7 @@ import { DatabaseContextProps, } from '../../../contexts/DatabaseContext'; import type { ConnectionObject } from '../../../sql/types'; +import { getErrorMessage } from '../../utils/error'; interface Props { children: ReactNode; @@ -33,10 +34,15 @@ function ConnectionStack({ children }: Props) { }; }, []); + // TODO we might need to change that into the proper route as reload will not work const handleConnectTo = useCallback( async (params: ConnectionObject) => { - await window.sql.openConnection(params); - // setConnectionNameList((prev) => [...prev, params.name]); + try { + await window.sql.openConnection(params); + setConnectionNameList((prev) => [...prev, params.name]); + } catch (error: unknown) { + console.error(getErrorMessage(error)); + } navigate(`/connections/${params.name}`); }, diff --git a/src/renderer/utils/error.tsx b/src/renderer/utils/error.tsx new file mode 100644 index 0000000..a6bcef6 --- /dev/null +++ b/src/renderer/utils/error.tsx @@ -0,0 +1,11 @@ +export function getErrorMessage(error: unknown, fallback?: string): string { + if (typeof error === 'string') { + return error; + } + + if (error instanceof Error) { + return error.message; + } + + return fallback ?? 'An unknown error occurred'; +} diff --git a/src/sql/index.ts b/src/sql/index.ts index debef63..25dcf8d 100644 --- a/src/sql/index.ts +++ b/src/sql/index.ts @@ -25,6 +25,13 @@ class ConnectionStack { async connect(params: ConnectionObject): Promise { const { name, ...rest } = params; + // don't connect twice to the same connection + if (this.connections.has(name)) { + throw new Error(`Connection already opened on "${name}"`); + } + + console.log(`[SQL] Open connection to "${name}"`); + const connection = await createConnection(rest); await connection.connect(); @@ -34,7 +41,7 @@ class ConnectionStack { async executeQuery(connectionName: string, query: string): QueryResult { const connection = this.#getConnection(connectionName); - console.log(`[SQL] Execute query "${query}"`); + console.log(`[SQL] Execute query on "${connectionName}": "${query}"`); return await connection.query(query); }