Files
SuperCharged-Claude-Code-Up…/services/database.js
uroma 1fbc565a66 feat: add session move endpoint and project-session cascading delete
- Add sessions table to database with projectId and deletedAt columns
- Create POST /api/sessions/:id/move endpoint to reassign sessions
- Update DELETE /api/projects/:id to cascade soft-delete to sessions
- Support moving sessions between projects or to unassigned state
- Handle both active (in-memory) and historical sessions

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-19 16:55:15 +00:00

99 lines
2.5 KiB
JavaScript

const Database = require('better-sqlite3');
const path = require('path');
/**
* Initialize SQLite database with projects schema
*/
function initializeDatabase() {
// Database file in project root
const dbPath = path.join(__dirname, '..', 'database.sqlite');
// Initialize database connection
const db = new Database(dbPath);
// Enable WAL mode for better concurrency
db.pragma('journal_mode = WAL');
// Drop existing table to remove UNIQUE constraint (migration)
// In production, use proper migrations instead
try {
db.exec(`DROP TABLE IF EXISTS projects`);
console.log('Dropped old projects table for schema migration');
} catch (error) {
// Table might not exist, which is fine
}
// Create projects table
db.exec(`
CREATE TABLE IF NOT EXISTS projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
icon TEXT DEFAULT '📁',
color TEXT DEFAULT '#4a9eff',
path TEXT NOT NULL,
createdAt TEXT NOT NULL,
lastActivity TEXT NOT NULL,
deletedAt TEXT NULL
)
`);
// Create index on deletedAt for efficient soft-delete queries
db.exec(`
CREATE INDEX IF NOT EXISTS idx_projects_deletedAt ON projects(deletedAt)
`);
// Create index on name for efficient name lookups
db.exec(`
CREATE INDEX IF NOT EXISTS idx_projects_name ON projects(name)
`);
// Create sessions table
db.exec(`
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
projectId INTEGER NULL,
deletedAt TEXT NULL,
FOREIGN KEY (projectId) REFERENCES projects(id) ON DELETE SET NULL
)
`);
// Create index on projectId for efficient session queries
db.exec(`
CREATE INDEX IF NOT EXISTS idx_sessions_projectId ON sessions(projectId)
`);
// Create index on deletedAt for efficient soft-delete queries
db.exec(`
CREATE INDEX IF NOT EXISTS idx_sessions_deletedAt ON sessions(deletedAt)
`);
return db;
}
/**
* Initialize database with requireAuth check
*/
let dbInstance = null;
function getDatabase() {
if (!dbInstance) {
try {
dbInstance = initializeDatabase();
console.log('Database initialized successfully');
} catch (error) {
console.error('Failed to initialize database:', error);
throw error;
}
}
return dbInstance;
}
// Initialize database immediately
const db = getDatabase();
module.exports = {
db,
getDatabase
};