Files
ERitors-Scribe-Desktop/electron/database/database.service.ts
natreex 9648d9e9be Upgrade database schema to version 2 and remove unused meta_* columns
- Increment `SCHEMA_VERSION` to 2 in `schema.ts`.
- Remove all `meta_*` columns from database tables.
- Add migration logic to handle schema upgrades and clean up unused columns.
- Modify database models and repository methods to exclude `meta_*` fields for stricter typings and improved structure.
- Refactor and optimize query statements across repositories to align with new schema changes.
2025-11-26 19:17:40 -05:00

99 lines
2.6 KiB
TypeScript

import sqlite3 from 'node-sqlite3-wasm';
import path from 'path';
import { app } from 'electron';
import { initializeSchema, runMigrations } from './schema.js';
// Type alias for compatibility
export type Database = sqlite3.Database;
/**
* DatabaseService - Manages SQLite database connection ONLY
* No business logic, no CRUD operations
* Just connection management and encryption key storage
*/
export class DatabaseService {
private db: Database | null = null;
private userEncryptionKey: string | null = null;
private userId: string | null = null;
constructor() {}
/**
* Initialize the database for a specific user
* @param userId - User ID for encryption key
* @param encryptionKey - User's encryption key (generated at first login)
*/
initialize(userId: string, encryptionKey: string): void {
if (this.db) {
this.close();
}
// Get user data directory
const userDataPath = app.getPath('userData');
const dbPath = path.join(userDataPath, `eritors-local-${userId}.db`);
this.db = new sqlite3.Database(dbPath);
this.userEncryptionKey = encryptionKey;
this.userId = userId;
// Initialize schema (creates tables if they don't exist)
initializeSchema(this.db);
// Run migrations (updates existing tables if needed)
runMigrations(this.db);
console.log(`Database initialized for user ${userId} at ${dbPath}`);
}
/**
* Close the database connection
*/
close(): void {
if (this.db) {
this.db.close();
this.db = null;
this.userEncryptionKey = null;
this.userId = null;
}
}
/**
* Check if database is initialized
*/
isInitialized(): boolean {
return this.db !== null && this.userEncryptionKey !== null;
}
/**
* Get database connection
* Use this in repositories and model classes
*/
getDb(): Database | null {
return this.db;
}
/**
* Get user encryption key
*/
getEncryptionKey(): string | null {
return this.userEncryptionKey;
}
/**
* Get current user ID
*/
getUserId(): string | null {
return this.userId;
}
}
// Singleton instance
let dbServiceInstance: DatabaseService | null = null;
export function getDatabaseService(): DatabaseService {
if (!dbServiceInstance) {
dbServiceInstance = new DatabaseService();
}
return dbServiceInstance;
}