diff --git a/apps/desktop/src/db/index.ts b/apps/desktop/src/db/index.ts index ff66bbd..39e4a45 100644 --- a/apps/desktop/src/db/index.ts +++ b/apps/desktop/src/db/index.ts @@ -18,6 +18,7 @@ export const db = drizzle(`file:${dbPath}`, { // Initialize database with migrations let isInitialized = false; +let dbConnection: null | typeof db = null; import { logger } from "../main/logger"; @@ -27,6 +28,9 @@ export async function initializeDatabase() { } try { + // Store the connection for later cleanup + dbConnection = db; + // Determine the correct migrations folder path const isDev = process.env.NODE_ENV === "development" || !app.isPackaged; let migrationsPath: string; @@ -73,3 +77,14 @@ export async function initializeDatabase() { process.exit(1); } } + +export async function closeDatabase() { + if (dbConnection) { + db.$client.close(); + dbConnection = null; + isInitialized = false; + dbConnection = null; + isInitialized = false; + logger.db.info("Database connection closed successfully"); + } +} diff --git a/apps/desktop/src/trpc/routers/settings.ts b/apps/desktop/src/trpc/routers/settings.ts index b45d732..8aaf500 100644 --- a/apps/desktop/src/trpc/routers/settings.ts +++ b/apps/desktop/src/trpc/routers/settings.ts @@ -2,7 +2,7 @@ import { observable } from "@trpc/server/observable"; import { z } from "zod"; import { app } from "electron"; import { createRouter, procedure } from "../trpc"; -import { dbPath } from "../../db"; +import { dbPath, closeDatabase } from "../../db"; import * as fs from "fs/promises"; // FormatterConfig schema @@ -557,6 +557,15 @@ export const settingsRouter = createRouter({ logger.main.info("Resetting app - deleting all data"); } + // Close database connection before deleting the file + if (logger) { + logger.main.info("Closing database connection before reset"); + } + await closeDatabase(); + + // Add a small delay to ensure the connection is fully closed on Windows + await new Promise((resolve) => setTimeout(resolve, 100)); + // Delete the database file await fs.unlink(dbPath);