34 lines
832 B
TypeScript
34 lines
832 B
TypeScript
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import Database from "better-sqlite3";
|
|
import {
|
|
drizzle,
|
|
type BetterSQLite3Database,
|
|
} from "drizzle-orm/better-sqlite3";
|
|
|
|
export interface DatabaseContext {
|
|
db: BetterSQLite3Database;
|
|
sqlite: Database.Database;
|
|
close: () => void;
|
|
}
|
|
|
|
export type AppDatabase = DatabaseContext["db"];
|
|
|
|
export function createDatabaseContext(filename: string): DatabaseContext {
|
|
if (filename !== ":memory:") {
|
|
const parentDirectory = path.dirname(path.resolve(filename));
|
|
if (!fs.existsSync(parentDirectory)) {
|
|
fs.mkdirSync(parentDirectory, { recursive: true });
|
|
}
|
|
}
|
|
|
|
const sqlite = new Database(filename);
|
|
sqlite.pragma("foreign_keys = ON");
|
|
const database = drizzle(sqlite);
|
|
return {
|
|
db: database,
|
|
sqlite,
|
|
close: () => sqlite.close(),
|
|
};
|
|
}
|