Skip to content

Commit

Permalink
avoid connecting twice
Browse files Browse the repository at this point in the history
  • Loading branch information
jdeniau committed Mar 5, 2024
1 parent 012d788 commit a76f5cd
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/renderer/component/Connection/ConnectionStack.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
DatabaseContextProps,
} from '../../../contexts/DatabaseContext';
import type { ConnectionObject } from '../../../sql/types';
import { getErrorMessage } from '../../utils/error';

interface Props {
children: ReactNode;
Expand All @@ -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}`);
},
Expand Down
11 changes: 11 additions & 0 deletions src/renderer/utils/error.tsx
Original file line number Diff line number Diff line change
@@ -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';
}
9 changes: 8 additions & 1 deletion src/sql/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ class ConnectionStack {
async connect(params: ConnectionObject): Promise<void> {
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();

Expand All @@ -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);
}
Expand Down

0 comments on commit a76f5cd

Please sign in to comment.