Skip to content

Commit

Permalink
clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
liuliu-dev committed Feb 14, 2025
1 parent 6e52778 commit 653e368
Show file tree
Hide file tree
Showing 12 changed files with 142 additions and 90 deletions.
6 changes: 5 additions & 1 deletion graphql-server/schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ type CurrentDatabaseState {
currentDatabase: String
}

type DoltServerStatus {
active: Boolean
}

type DiffStat {
rowsUnmodified: Float!
rowsAdded: Float!
Expand Down Expand Up @@ -328,7 +332,7 @@ type Query {
currentConnection: DatabaseConnection
storedConnections: [DatabaseConnection!]!
databases: [String!]!
checkConnection(connectionUrl: String!, name: String!, port: String, hideDoltFeatures: Boolean, useSSL: Boolean, type: DatabaseType, isLocalDolt: Boolean): Boolean!
doltServerStatus(connectionUrl: String!, name: String!, port: String, hideDoltFeatures: Boolean, useSSL: Boolean, type: DatabaseType, isLocalDolt: Boolean): DoltServerStatus!
databasesByConnection(connectionUrl: String!, name: String!, port: String, hideDoltFeatures: Boolean, useSSL: Boolean, type: DatabaseType, isLocalDolt: Boolean): [String!]!
schemas(databaseName: String!, refName: String!): [String!]!
doltDatabaseDetails: DoltDatabaseDetails!
Expand Down
20 changes: 14 additions & 6 deletions graphql-server/src/databases/database.resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ class CurrentDatabaseState {
currentDatabase?: string;
}

@ObjectType()
class DoltServerStatus {
@Field({ nullable: true })
active?: boolean;
}

@ArgsType()
class RemoveDatabaseConnectionArgs {
@Field()
Expand Down Expand Up @@ -125,22 +131,24 @@ export class DatabaseResolver {
return dbs;
}

@Query(_returns => Boolean)
async checkConnection(
// Checking if the internal dolt server is running
@Query(_returns => DoltServerStatus)
async doltServerStatus(
@Args() args: AddDatabaseConnectionArgs,
): Promise<boolean> {
): Promise<DoltServerStatus> {
// if current connection is the same as the internal dolt server, return true
if (this.conn.getWorkbenchConfig()?.connectionUrl === args.connectionUrl) {
return true;
return { active: true };
}
const workbenchConfig = getWorkbenchConfigFromArgs(args);
try {
const ds = getDataSource(workbenchConfig);
await ds.initialize();
await ds.query("SELECT 1");
return true;
return { active: true };
} catch (error) {
console.error("Error checking connection:", error.message);

Check warning on line 150 in graphql-server/src/databases/database.resolver.ts

View workflow job for this annotation

GitHub Actions / ci

Unexpected console statement
return false;
return { active: false };
}
}

Expand Down
30 changes: 18 additions & 12 deletions web/main/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { createWindow } from "./helpers";
import { initMenu } from "./helpers/menu";
import { removeDoltServerFolder, startServer } from "./doltServer";
import { ChildProcess } from "child_process";
import { L } from "ace-builds-internal/lib/bidiutil";

const isProd = process.env.NODE_ENV === "production";
const userDataPath = app.getPath("userData");
Expand Down Expand Up @@ -222,16 +221,6 @@ ipcMain.handle("toggle-left-sidebar", () => {
mainWindow.webContents.send("toggle-left-sidebar");
});

function getErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
} else if (typeof error === "string") {
return error;
} else {
return "An unknown error occurred";
}
}

ipcMain.handle(
"start-dolt-server",
async (event, connectionName: string, port: string, init?: boolean) => {
Expand All @@ -253,6 +242,7 @@ ipcMain.handle(
ipcMain.handle(
"remove-dolt-connection",
async (event, connectionName: string) => {
// if doltServerProcess is running, kill it
if (doltServerProcess) {
doltServerProcess.kill();
doltServerProcess = null;
Expand All @@ -262,11 +252,27 @@ ipcMain.handle(
: path.join(__dirname, "..", "build", "databases", connectionName);

try {
await removeDoltServerFolder(dbFolderPath);
const { errorMsg } = await removeDoltServerFolder(
dbFolderPath,
mainWindow,
);
if (errorMsg) {
throw new Error(errorMsg);
}
} catch (error) {
throw new Error(getErrorMessage(error));
} finally {
return "Connection removed successfully";
}
},
);

function getErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
} else if (typeof error === "string") {
return error;
} else {
return "An unknown error occurred";
}
}
34 changes: 22 additions & 12 deletions web/main/doltServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ export async function startServer(
port: string,
init?: boolean,
): Promise<ChildProcess | null> {
// Set the path for the database folder
// In production, it's in the userData directory
// In development, it's in the build directory since the development userData directory clears its contents every time the app is rerun in dev mode
const dbFolderPath = isProd
? path.join(app.getPath("userData"), "databases", connectionName)
: path.join(__dirname, "..", "build", "databases", connectionName);
Expand All @@ -32,10 +35,8 @@ export async function startServer(

// Initialize and start the server without checking if it's already running
await initializeDoltRepository(doltPath, dbFolderPath, mainWindow);
return await startServerProcess(doltPath, dbFolderPath, port, mainWindow);
} else {
return await startServerProcess(doltPath, dbFolderPath, port, mainWindow);
}
return await startServerProcess(doltPath, dbFolderPath, port, mainWindow);
} catch (error) {
console.error("Failed to set up Dolt server:", error);
throw error;
Expand Down Expand Up @@ -73,7 +74,7 @@ function getDoltPaths(): string {
}
}

//initialize the Dolt repository, running dolt init in dbFolderPath
//initialize the Dolt repository by running `dolt init` in dbFolderPath
function initializeDoltRepository(
doltPath: string,
dbFolderPath: string,
Expand All @@ -86,8 +87,10 @@ function initializeDoltRepository(
mainWindow.webContents.send("server-error", initErr);

// Clean up: Delete the folder
const { errorMsg: removeFolderErr } =
removeDoltServerFolder(dbFolderPath);
const { errorMsg: removeFolderErr } = removeDoltServerFolder(
dbFolderPath,
mainWindow,
);
if (removeFolderErr) {
mainWindow.webContents.send("server-error", removeFolderErr);
}
Expand All @@ -106,8 +109,10 @@ function initializeDoltRepository(
mainWindow.webContents.send("server-error", stderr);

// Clean up: Delete the folder
const { errorMsg: removeFolderErr } =
removeDoltServerFolder(dbFolderPath);
const { errorMsg: removeFolderErr } = removeDoltServerFolder(
dbFolderPath,
mainWindow,
);
if (removeFolderErr) {
mainWindow.webContents.send("server-error", removeFolderErr);
}
Expand All @@ -124,7 +129,7 @@ function initializeDoltRepository(
});
}

// start the Dolt SQL server
// start the Dolt SQL server and return the server process
function startServerProcess(
doltPath: string,
dbFolderPath: string,
Expand Down Expand Up @@ -170,8 +175,6 @@ function startServerProcess(
mainWindow.webContents.send("server-error", errorMessage);

reject(new Error(errorMessage));
} else {
mainWindow.webContents.send("server-log", errorMessage);
}

// Resolve the promise when the server is ready
Expand All @@ -185,10 +188,17 @@ function startServerProcess(
});
}

export function removeDoltServerFolder(dbFolderPath: string): ErrorReturnType {
export function removeDoltServerFolder(
dbFolderPath: string,
mainWindow: BrowserWindow,
): ErrorReturnType {
// Delete the folder
fs.rm(dbFolderPath, { recursive: true, force: true }, err => {
if (err) {
mainWindow.webContents.send(
`server-error:Failed to delete folder, folder:${dbFolderPath}, `,
err,
);
return {
errorMsg: `Failed to delete folder: ${err}`,
};
Expand Down
10 changes: 6 additions & 4 deletions web/renderer/components/DatabaseHeaderAndNav/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,22 @@ export const DATABASES_BY_CONNECTION = gql`
}
`;

export const CHECK_CONNECTION = gql`
query CheckConnection(
export const DOLT_SERVER_STATUS = gql`
query DoltServerStatus(
$connectionUrl: String!
$name: String!
$hideDoltFeatures: Boolean
$useSSL: Boolean
$type: DatabaseType
) {
checkConnection(
doltServerStatus(
connectionUrl: $connectionUrl
name: $name
hideDoltFeatures: $hideDoltFeatures
useSSL: $useSSL
type: $type
)
) {
active
}
}
`;
4 changes: 4 additions & 0 deletions web/renderer/components/DeleteModal/index.module.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
.bold {
@apply font-semibold;
}

.alert {
@apply text-red-400 font-semibold;
}
12 changes: 10 additions & 2 deletions web/renderer/components/DeleteModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ type Props<TData, TVariables> = {
assetId?: string;
btnText?: string;
mutationProps: MutationProps<TData, TVariables>;
callback?: (d: TData) => void;
callback?: (d: TData) => Error | void;
children?: ReactNode;
className?: string;
buttonDataCy?: string;
alertMessage?: string;
};

export default function DeleteModal<TData, TVariables>({
Expand Down Expand Up @@ -48,7 +49,13 @@ export default function DeleteModal<TData, TVariables>({
variables: mutationProps.variables,
});
if (!success || !data) return;
if (props.callback) props.callback(data);
if (props.callback) {
const error = props.callback(data);
if (error) {
setErr(error);
return;
}
}
onClose();
};

Expand Down Expand Up @@ -78,6 +85,7 @@ export default function DeleteModal<TData, TVariables>({
{props.cannotBeUndone && " This cannot be undone."}
</p>
)}
{props.alertMessage && <p className={css.alert}>{props.alertMessage}</p>}
{children}
</Modal>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { getDatabaseType } from "@components/DatabaseTypeLabel";
import { Button, ErrorMsg, Loader } from "@dolthub/react-components";
import {
DatabaseConnectionFragment,
useCheckConnectionQuery,
} from "@gen/graphql-types";
import { DatabaseConnectionFragment } from "@gen/graphql-types";
import { IoMdClose } from "@react-icons/all-files/io/IoMdClose";
import Image from "next/legacy/image";
import cx from "classnames";
Expand All @@ -26,15 +23,12 @@ export default function Item({
borderClassName,
shorterLine,
}: Props) {
const { onAdd, err, loading } = useAddConnection(conn);
const res = useCheckConnectionQuery({
variables: conn,
});
const { onAdd, err, loading, doltServerIsActive } = useAddConnection(conn);

const type = getDatabaseType(conn.type ?? undefined, !!conn.isDolt);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!res.data?.checkConnection) {
if (!doltServerIsActive) {
try {
await window.ipc.invoke(
"start-dolt-server",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,20 @@ export default function ExistingConnections(props: Props) {
const [deleteModalOpen, setDeleteModalOpen] = useState(false);
const [connectionNameToDelete, setConnectionNameToDelete] = useState("");
const [isLocalDolt, setIsLocalDolt] = useState(false);

const onDeleteClicked = (name: string, local: boolean) => {
setConnectionNameToDelete(name);
setDeleteModalOpen(true);
setIsLocalDolt(local);
};

// TODO: need to reveal the remove folder error
const removeLocalDoltFolder = async (name: string) => {
const removeLocalDoltFolder = () => {
try {
const result = await window.ipc.invoke("remove-dolt-connection", name);
console.log(result);
window.ipc.invoke("remove-dolt-connection", connectionNameToDelete);
} catch (error) {
console.error("Failed to remove local Dolt server:", error);
return new Error(`Failed to remove local Dolt server: ${error}`);
}
return undefined;
};

const router = useRouter();
Expand Down Expand Up @@ -99,9 +98,10 @@ export default function ExistingConnections(props: Props) {
variables: { name: connectionNameToDelete },
refetchQueries: [{ query: StoredConnectionsDocument }],
}}
callback={
callback={isLocalDolt ? () => removeLocalDoltFolder() : undefined}
alertMessage={
isLocalDolt
? async () => removeLocalDoltFolder(connectionNameToDelete)
? "This action will permanently delete the local Dolt server and all associated data stored within it. This cannot be undone."
: undefined
}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
DatabaseConnectionFragment,
useAddDatabaseConnectionMutation,
useDoltServerStatusQuery,
} from "@gen/graphql-types";
import { ApolloErrorType } from "@lib/errors/types";
import { maybeDatabase } from "@lib/urls";
Expand All @@ -10,14 +11,17 @@ type ReturnType = {
onAdd: () => Promise<void>;
err: ApolloErrorType;
loading: boolean;
doltServerIsActive?: boolean;
};

export default function useAddConnection(
conn: DatabaseConnectionFragment,
): ReturnType {
const router = useRouter();
const [addDb, res] = useAddDatabaseConnectionMutation();

const doltServerStatus = useDoltServerStatusQuery({
variables: conn,
});
const onAdd = async () => {
try {
const db = await addDb({ variables: conn });
Expand All @@ -34,5 +38,10 @@ export default function useAddConnection(
}
};

return { onAdd, err: res.error, loading: res.loading };
return {
onAdd,
err: res.error,
loading: res.loading,
doltServerIsActive: !!doltServerStatus.data?.doltServerStatus.active,
};
}
Loading

0 comments on commit 653e368

Please sign in to comment.