53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { DatabaseSync } from "node:sqlite";
|
|
|
|
type DatabaseGlobal = typeof globalThis & {
|
|
plannerDatabase?: DatabaseSync;
|
|
plannerDatabasePath?: string;
|
|
};
|
|
|
|
const schemaPath = path.join(process.cwd(), "db", "schema.sql");
|
|
const defaultDatabasePath = path.join(process.cwd(), "data", "planner.sqlite");
|
|
|
|
export function getDatabase() {
|
|
const databasePath = process.env.TASKS_DB_PATH ?? defaultDatabasePath;
|
|
const globalDatabase = globalThis as DatabaseGlobal;
|
|
|
|
if (
|
|
globalDatabase.plannerDatabase &&
|
|
globalDatabase.plannerDatabasePath === databasePath
|
|
) {
|
|
return globalDatabase.plannerDatabase;
|
|
}
|
|
|
|
if (globalDatabase.plannerDatabase) {
|
|
globalDatabase.plannerDatabase.close();
|
|
delete globalDatabase.plannerDatabase;
|
|
delete globalDatabase.plannerDatabasePath;
|
|
}
|
|
|
|
fs.mkdirSync(path.dirname(databasePath), { recursive: true });
|
|
|
|
const database = new DatabaseSync(databasePath);
|
|
const schema = fs.readFileSync(schemaPath, "utf8");
|
|
|
|
database.exec("PRAGMA foreign_keys = ON;");
|
|
database.exec(schema);
|
|
|
|
globalDatabase.plannerDatabase = database;
|
|
globalDatabase.plannerDatabasePath = databasePath;
|
|
|
|
return database;
|
|
}
|
|
|
|
export function closeDatabaseForTests() {
|
|
const globalDatabase = globalThis as DatabaseGlobal;
|
|
|
|
if (globalDatabase.plannerDatabase) {
|
|
globalDatabase.plannerDatabase.close();
|
|
delete globalDatabase.plannerDatabase;
|
|
delete globalDatabase.plannerDatabasePath;
|
|
}
|
|
}
|