47 lines
1.7 KiB
TypeScript
47 lines
1.7 KiB
TypeScript
import { Database } from 'bun:sqlite';
|
|
import { env } from 'bun';
|
|
import { drizzle } from 'drizzle-orm/bun-sqlite';
|
|
// import { migrate } from 'drizzle-orm/bun-sqlite/migrator';
|
|
import { createWrappedTimer } from '@server/wrapped-timer';
|
|
|
|
function initDb() {
|
|
// global.db.exec('PRAGMA journal_mode = delete');
|
|
global.db.exec('PRAGMA journal_mode = WAL');
|
|
global.db.exec('PRAGMA synchronous = NORMAL');
|
|
global.db.exec('PRAGMA auto_vacuum = INCREMENTAL');
|
|
global.db.exec('PRAGMA wal_autocheckpoint = 1000');
|
|
}
|
|
|
|
function incrementalVacuumDb() {
|
|
global.db.exec('PRAGMA incremental_vacuum');
|
|
}
|
|
|
|
function optimizeDb() {
|
|
global.db.exec('PRAGMA optimize');
|
|
}
|
|
|
|
function vacuumDb() {
|
|
global.db.exec('vacuum');
|
|
}
|
|
|
|
if (global.db === undefined || global.drizzleDB === undefined) {
|
|
global.db = new Database(`${env.SQLITE_DB_PATH}/${env.SQLITE_DB_NAME}`, { create: true, strict: true });
|
|
initDb();
|
|
global.drizzleDB = drizzle(global.db);
|
|
// migrate(global.drizzleDB, { migrationsFolder: './drizzle' });
|
|
}
|
|
|
|
const incrementalVacuumInterval = 1000 * 30; // 30 seconds
|
|
const incrementalVacuumRunnable = createWrappedTimer('databaseIncrementalVacuum', incrementalVacuumDb, incrementalVacuumInterval);
|
|
|
|
setTimeout(incrementalVacuumRunnable.callback, 0);
|
|
const optimizeInterval = 1000 * 60 * 30; // 30 minutes
|
|
const optimizeRunnable = createWrappedTimer('databaseOptimize', optimizeDb, optimizeInterval);
|
|
setTimeout(optimizeRunnable.callback, 0);
|
|
|
|
const vacuumInterval = 1000 * 60 * 60 * 24; // 24 hours
|
|
const vacuumRunnable = createWrappedTimer('databaseVacuum', vacuumDb, vacuumInterval);
|
|
setTimeout(vacuumRunnable.callback, 0);
|
|
|
|
export const db = global.db;
|
|
export const drizzleDB = global.drizzleDB;
|