2024-09-27 21:39:03 -04:00
|
|
|
import { drizzle } from "drizzle-orm/better-sqlite3";
|
|
|
|
import Database from "better-sqlite3";
|
2024-09-27 21:49:52 -04:00
|
|
|
import * as schema from "@server/db/schema";
|
2024-10-26 23:37:25 -04:00
|
|
|
import { __DIRNAME, APP_PATH } from "@server/config";
|
2024-09-28 14:02:06 -04:00
|
|
|
import path from "path";
|
2024-10-26 23:37:25 -04:00
|
|
|
import fs from "fs";
|
|
|
|
import logger from "@server/logger";
|
|
|
|
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
|
2024-09-27 21:39:03 -04:00
|
|
|
|
2024-10-12 18:21:31 -04:00
|
|
|
const location = path.join(APP_PATH, "db", "db.sqlite");
|
2024-10-06 11:13:50 -04:00
|
|
|
|
2024-10-26 23:37:25 -04:00
|
|
|
let dbExists = true;
|
|
|
|
if (!fs.existsSync(location)) {
|
|
|
|
dbExists = false;
|
|
|
|
}
|
|
|
|
|
2024-10-06 11:13:50 -04:00
|
|
|
const sqlite = new Database(location);
|
2024-09-27 21:39:03 -04:00
|
|
|
export const db = drizzle(sqlite, { schema });
|
|
|
|
|
2024-10-26 23:37:25 -04:00
|
|
|
if (!dbExists && process.env.ENVIRONMENT === "prod") {
|
|
|
|
logger.info("Running migrations...");
|
|
|
|
try {
|
|
|
|
migrate(db, {
|
|
|
|
migrationsFolder: path.join(__DIRNAME, "migrations"),
|
|
|
|
});
|
|
|
|
logger.info("Migrations completed successfully.");
|
|
|
|
} catch (error) {
|
|
|
|
logger.error("Error running migrations:", error);
|
|
|
|
process.exit(1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-27 21:39:03 -04:00
|
|
|
export default db;
|