UNPKG

quicklite

Version:

A lightweight ORM toolkit for SQLite in Node.js applications

95 lines 2.9 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DatabaseManager = void 0; const better_sqlite3_1 = __importDefault(require("better-sqlite3")); const path_1 = __importDefault(require("path")); const fs_1 = __importDefault(require("fs")); /** * Manages SQLite database connection */ class DatabaseManager { /** * Creates a new DatabaseManager instance * @param options Database connection options */ constructor(options) { this.db = null; this.dbOptions = options; this.ensureDatabaseDirectory(); this.init(); } /** * Gets or creates a DatabaseManager instance * @param options Database connection options * @returns DatabaseManager instance */ static getInstance(options) { const key = options.dbPath; if (!DatabaseManager.instances.has(key)) { DatabaseManager.instances.set(key, new DatabaseManager(options)); } return DatabaseManager.instances.get(key); } /** * Ensures that the database directory exists */ ensureDatabaseDirectory() { const dbDir = path_1.default.dirname(this.dbOptions.dbPath); if (!fs_1.default.existsSync(dbDir)) { fs_1.default.mkdirSync(dbDir, { recursive: true }); } } /** * Initializes the database connection */ init() { try { this.db = new better_sqlite3_1.default(this.dbOptions.dbPath, this.dbOptions.sqliteOptions); // Set pragmas for better performance if (this.dbOptions.enableWAL !== false) { this.db.pragma('journal_mode = WAL'); } if (this.dbOptions.enableForeignKeys !== false) { this.db.pragma('foreign_keys = ON'); } } catch (error) { console.error('Database initialization failed:', error); this.db = null; throw error; } } /** * Gets the database instance * @returns SQLite database instance */ getDatabase() { if (!this.db) { throw new Error('Database has not been initialized or was closed'); } return this.db; } /** * Closes the database connection */ closeDatabase() { if (this.db) { this.db.close(); this.db = null; DatabaseManager.instances.delete(this.dbOptions.dbPath); } } /** * Gets the database file path * @returns Database file path */ getDatabasePath() { return this.dbOptions.dbPath; } } exports.DatabaseManager = DatabaseManager; DatabaseManager.instances = new Map(); //# sourceMappingURL=DatabaseManager.js.map