import db from './src/lib/db.js'; console.log('Starting migration to add team_lead role to users table constraint...'); try { // Disable foreign key constraints temporarily db.pragma('foreign_keys = OFF'); console.log('Disabled foreign key constraints'); // Since SQLite doesn't support modifying CHECK constraints directly, // we need to recreate the table with the new constraint // First, create a backup table with current data db.exec('CREATE TABLE users_backup AS SELECT * FROM users'); console.log('Created backup table'); // Drop the original table db.exec('DROP TABLE users'); console.log('Dropped original table'); // Recreate the table with the updated constraint db.exec(` CREATE TABLE users ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), name TEXT NOT NULL, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT CHECK(role IN ('admin', 'team_lead', 'project_manager', 'user', 'read_only')) DEFAULT 'user', created_at TEXT DEFAULT CURRENT_TIMESTAMP, updated_at TEXT DEFAULT CURRENT_TIMESTAMP, is_active INTEGER DEFAULT 1, last_login TEXT, failed_login_attempts INTEGER DEFAULT 0, locked_until TEXT, can_be_assigned INTEGER DEFAULT 1, initial TEXT ) `); console.log('Created new table with updated constraint'); // Copy data back from backup db.exec(` INSERT INTO users ( id, name, username, password_hash, role, created_at, updated_at, is_active, last_login, failed_login_attempts, locked_until, can_be_assigned, initial ) SELECT id, name, username, password_hash, role, created_at, updated_at, is_active, last_login, failed_login_attempts, locked_until, can_be_assigned, initial FROM users_backup `); console.log('Copied data back from backup'); // Drop the backup table db.exec('DROP TABLE users_backup'); console.log('Dropped backup table'); // Re-enable foreign key constraints db.pragma('foreign_keys = ON'); console.log('Re-enabled foreign key constraints'); // Verify the migration const userCount = db.prepare('SELECT COUNT(*) as count FROM users').get(); console.log(`✅ Migration completed successfully! Users table now has ${userCount.count} records`); // Verify the constraint allows the new role console.log('✅ CHECK constraint now includes: admin, team_lead, project_manager, user, read_only'); } catch (error) { console.error('❌ Migration failed:', error.message); console.error('You may need to restore from backup manually'); process.exit(1); }