Refactor logging in cleanup scripts to use report array for improved output management
Updated various cleanup scripts to replace console.log statements with a report array, enhancing the output handling and allowing for better formatting of messages. This change improves the readability of logs and ensures consistent reporting across different cleanup operations, including database connection status, index management, and summary reports.
This commit is contained in:
@@ -3,6 +3,8 @@ import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const report = [];
|
||||
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
user: process.env.DB_USER || 'root',
|
||||
@@ -56,9 +58,9 @@ async function cleanupDuplicates(connection, table) {
|
||||
for (const idxName of dropNames) {
|
||||
try {
|
||||
await connection.execute(`DROP INDEX \`${idxName}\` ON \`${table}\``);
|
||||
console.log(`[drop] ${table}: ${idxName}`);
|
||||
report.push(`[drop] ${table}: ${idxName}`);
|
||||
} catch (e) {
|
||||
console.warn(`[warn] ${table}: konnte Index ${idxName} nicht löschen: ${e.code || e.message}`);
|
||||
report.push(`[warn] ${table}: konnte Index ${idxName} nicht löschen: ${e.code || e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,11 +71,11 @@ async function cleanupDuplicates(connection, table) {
|
||||
async function main() {
|
||||
let connection;
|
||||
try {
|
||||
console.log('Connecting to DB:', dbConfig);
|
||||
report.push(`Connecting to DB: ${JSON.stringify(dbConfig)}`);
|
||||
connection = await mysql.createConnection(dbConfig);
|
||||
|
||||
const tables = await getTables(connection);
|
||||
console.log(`Found ${tables.length} tables`);
|
||||
report.push(`Found ${tables.length} tables`);
|
||||
|
||||
let totalBefore = 0;
|
||||
let totalAfter = 0;
|
||||
@@ -86,12 +88,15 @@ async function main() {
|
||||
totalDropped += dropped;
|
||||
}
|
||||
|
||||
console.log('Summary:', { totalBefore, totalAfter, totalDropped });
|
||||
report.push(`Summary: ${JSON.stringify({ totalBefore, totalAfter, totalDropped })}`);
|
||||
} catch (e) {
|
||||
console.error('Cleanup failed:', e);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
if (connection) await connection.end();
|
||||
if (report.length > 0) {
|
||||
process.stdout.write(`${report.join('\n')}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const report = [];
|
||||
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
user: process.env.DB_USER || 'root',
|
||||
@@ -26,13 +28,14 @@ async function cleanupUserTokenKeys() {
|
||||
const table = 'UserToken';
|
||||
|
||||
try {
|
||||
console.log('Connecting to DB:', dbConfig);
|
||||
report.push(`Connecting to DB: ${JSON.stringify(dbConfig)}`);
|
||||
connection = await mysql.createConnection(dbConfig);
|
||||
|
||||
console.log(`\nBefore cleanup (indexes on ${table}):`);
|
||||
report.push('');
|
||||
report.push(`Before cleanup (indexes on ${table}):`);
|
||||
let before = await getIndexSummary(connection, table);
|
||||
Object.entries(before).forEach(([name, info]) => {
|
||||
console.log(` - ${name} ${info.unique ? '(UNIQUE)' : ''} -> [${info.columns.join(', ')}]`);
|
||||
report.push(` - ${name} ${info.unique ? '(UNIQUE)' : ''} -> [${info.columns.join(', ')}]`);
|
||||
});
|
||||
|
||||
// Drop all non-PRIMARY indexes on UserToken
|
||||
@@ -42,9 +45,9 @@ async function cleanupUserTokenKeys() {
|
||||
for (const keyName of keyNames) {
|
||||
try {
|
||||
await connection.execute(`DROP INDEX \`${keyName}\` ON \`${table}\``);
|
||||
console.log(`Dropped index: ${keyName}`);
|
||||
report.push(`Dropped index: ${keyName}`);
|
||||
} catch (err) {
|
||||
console.warn(`Could not drop ${keyName}: ${err.code || err.message}`);
|
||||
report.push(`Could not drop ${keyName}: ${err.code || err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,9 +55,9 @@ async function cleanupUserTokenKeys() {
|
||||
// Unique on token (column is 'token')
|
||||
try {
|
||||
await connection.execute(`CREATE UNIQUE INDEX \`uniq_UserToken_token\` ON \`${table}\` (\`token\`)`);
|
||||
console.log('Created UNIQUE index: uniq_UserToken_token (token)');
|
||||
report.push('Created UNIQUE index: uniq_UserToken_token (token)');
|
||||
} catch (err) {
|
||||
console.warn('Could not create uniq_UserToken_token:', err.code || err.message);
|
||||
report.push(`Could not create uniq_UserToken_token: ${err.code || err.message}`);
|
||||
}
|
||||
|
||||
// Helpful index on user_id if column exists
|
||||
@@ -62,26 +65,31 @@ async function cleanupUserTokenKeys() {
|
||||
const [cols] = await connection.execute(`SHOW COLUMNS FROM \`${table}\` LIKE 'user_id'`);
|
||||
if (cols && cols.length > 0) {
|
||||
await connection.execute(`CREATE INDEX \`idx_UserToken_user_id\` ON \`${table}\` (\`user_id\`)`);
|
||||
console.log('Created INDEX: idx_UserToken_user_id (user_id)');
|
||||
report.push('Created INDEX: idx_UserToken_user_id (user_id)');
|
||||
} else {
|
||||
console.log('Column user_id not found, skip creating idx_UserToken_user_id');
|
||||
report.push('Column user_id not found, skip creating idx_UserToken_user_id');
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Could not create idx_UserToken_user_id:', err.code || err.message);
|
||||
report.push(`Could not create idx_UserToken_user_id: ${err.code || err.message}`);
|
||||
}
|
||||
|
||||
console.log(`\nAfter cleanup (indexes on ${table}):`);
|
||||
report.push('');
|
||||
report.push(`After cleanup (indexes on ${table}):`);
|
||||
const after = await getIndexSummary(connection, table);
|
||||
Object.entries(after).forEach(([name, info]) => {
|
||||
console.log(` - ${name} ${info.unique ? '(UNIQUE)' : ''} -> [${info.columns.join(', ')}]`);
|
||||
report.push(` - ${name} ${info.unique ? '(UNIQUE)' : ''} -> [${info.columns.join(', ')}]`);
|
||||
});
|
||||
|
||||
console.log('\nDone.');
|
||||
report.push('');
|
||||
report.push('Done.');
|
||||
} catch (err) {
|
||||
console.error('Cleanup failed:', err);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
if (connection) await connection.end();
|
||||
if (report.length > 0) {
|
||||
process.stdout.write(`${report.join('\n')}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,8 @@ const TEST_USERS = [
|
||||
];
|
||||
|
||||
async function createTestUsers() {
|
||||
console.log('Creating test users...\n');
|
||||
const report = [];
|
||||
report.push('Creating test users...');
|
||||
|
||||
try {
|
||||
// Get first club (or specify club ID)
|
||||
@@ -59,16 +60,16 @@ async function createTestUsers() {
|
||||
}
|
||||
|
||||
const club = clubs[0];
|
||||
console.log(`Using club: ${club.name} (ID: ${club.id})\n`);
|
||||
report.push(`Using club: ${club.name} (ID: ${club.id})`);
|
||||
|
||||
for (const userData of TEST_USERS) {
|
||||
console.log(`Creating user: ${userData.email} (${userData.role})...`);
|
||||
report.push(`Creating user: ${userData.email} (${userData.role})...`);
|
||||
|
||||
// Check if user already exists
|
||||
let user = await User.findOne({ where: { email: userData.email } });
|
||||
|
||||
if (user) {
|
||||
console.log(` ⚠️ User already exists, using existing user`);
|
||||
report.push(' ⚠️ User already exists, using existing user');
|
||||
} else {
|
||||
// Create user
|
||||
user = await User.create({
|
||||
@@ -76,7 +77,7 @@ async function createTestUsers() {
|
||||
password: userData.password,
|
||||
isActive: true
|
||||
});
|
||||
console.log(` ✓ User created`);
|
||||
report.push(' ✓ User created');
|
||||
}
|
||||
|
||||
// Check if user is already in club
|
||||
@@ -88,13 +89,13 @@ async function createTestUsers() {
|
||||
});
|
||||
|
||||
if (userClub) {
|
||||
console.log(` ⚠️ User already in club, updating role...`);
|
||||
report.push(' ⚠️ User already in club, updating role...');
|
||||
await userClub.update({
|
||||
role: userData.role,
|
||||
isOwner: userData.isOwner,
|
||||
approved: true
|
||||
});
|
||||
console.log(` ✓ Updated to role: ${userData.role}`);
|
||||
report.push(` ✓ Updated to role: ${userData.role}`);
|
||||
} else {
|
||||
// Add user to club
|
||||
userClub = await UserClub.create({
|
||||
@@ -104,31 +105,37 @@ async function createTestUsers() {
|
||||
isOwner: userData.isOwner,
|
||||
approved: true
|
||||
});
|
||||
console.log(` ✓ Added to club with role: ${userData.role}`);
|
||||
report.push(` ✓ Added to club with role: ${userData.role}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n✅ Test users created successfully!\n');
|
||||
report.push('');
|
||||
report.push('✅ Test users created successfully!');
|
||||
|
||||
// Show summary
|
||||
console.log('Summary:');
|
||||
console.log('========================================');
|
||||
console.log(`Club: ${club.name}`);
|
||||
console.log('\nTest Users:');
|
||||
report.push('Summary:');
|
||||
report.push('========================================');
|
||||
report.push(`Club: ${club.name}`);
|
||||
report.push('');
|
||||
report.push('Test Users:');
|
||||
|
||||
for (const userData of TEST_USERS) {
|
||||
console.log(` ${userData.email.padEnd(25)} | ${userData.role.padEnd(15)} | Password: test123`);
|
||||
report.push(` ${userData.email.padEnd(25)} | ${userData.role.padEnd(15)} | Password: test123`);
|
||||
}
|
||||
|
||||
console.log('\n========================================');
|
||||
console.log('You can now login with any of these users!');
|
||||
console.log('All passwords are: test123');
|
||||
report.push('');
|
||||
report.push('========================================');
|
||||
report.push('You can now login with any of these users!');
|
||||
report.push('All passwords are: test123');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error creating test users:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
await sequelize.close();
|
||||
if (report.length > 0) {
|
||||
process.stdout.write(`${report.join('\n')}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,8 @@ import sequelize from '../database.js';
|
||||
*/
|
||||
|
||||
async function migratePermissions() {
|
||||
console.log('Starting permissions migration...\n');
|
||||
const report = [];
|
||||
report.push('Starting permissions migration...');
|
||||
|
||||
try {
|
||||
// Get all clubs
|
||||
@@ -29,10 +30,11 @@ async function migratePermissions() {
|
||||
}]
|
||||
});
|
||||
|
||||
console.log(`Found ${clubs.length} club(s)\n`);
|
||||
report.push(`Found ${clubs.length} club(s)`);
|
||||
|
||||
for (const club of clubs) {
|
||||
console.log(`\n--- Club: ${club.name} (ID: ${club.id}) ---`);
|
||||
report.push(``);
|
||||
report.push(`--- Club: ${club.name} (ID: ${club.id}) ---`);
|
||||
|
||||
const userClubs = await UserClub.findAll({
|
||||
where: {
|
||||
@@ -47,15 +49,15 @@ async function migratePermissions() {
|
||||
});
|
||||
|
||||
if (userClubs.length === 0) {
|
||||
console.log(' No approved members found.');
|
||||
report.push(' No approved members found.');
|
||||
continue;
|
||||
}
|
||||
|
||||
// First user becomes owner
|
||||
const firstUser = userClubs[0];
|
||||
|
||||
console.log(` Members found: ${userClubs.length}`);
|
||||
console.log(` First member (will be owner): ${firstUser.user.email}`);
|
||||
report.push(` Members found: ${userClubs.length}`);
|
||||
report.push(` First member (will be owner): ${firstUser.user.email}`);
|
||||
|
||||
for (let i = 0; i < userClubs.length; i++) {
|
||||
const userClub = userClubs[i];
|
||||
@@ -71,12 +73,14 @@ async function migratePermissions() {
|
||||
|
||||
await userClub.save();
|
||||
|
||||
console.log(` ✓ Updated ${userClub.user.email}: role=${userClub.role}, isOwner=${userClub.isOwner}`);
|
||||
report.push(` ✓ Updated ${userClub.user.email}: role=${userClub.role}, isOwner=${userClub.isOwner}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n✅ Migration completed successfully!');
|
||||
console.log('\nSummary:');
|
||||
report.push('');
|
||||
report.push('✅ Migration completed successfully!');
|
||||
report.push('');
|
||||
report.push('Summary:');
|
||||
|
||||
// Show summary
|
||||
const owners = await UserClub.findAll({
|
||||
@@ -95,9 +99,9 @@ async function migratePermissions() {
|
||||
]
|
||||
});
|
||||
|
||||
console.log(`\nClub Owners (${owners.length}):`);
|
||||
report.push(`\nClub Owners (${owners.length}):`);
|
||||
for (const owner of owners) {
|
||||
console.log(` - ${owner.club.name}: ${owner.user.email}`);
|
||||
report.push(` - ${owner.club.name}: ${owner.user.email}`);
|
||||
}
|
||||
|
||||
const admins = await UserClub.count({
|
||||
@@ -107,15 +111,19 @@ async function migratePermissions() {
|
||||
where: { role: 'member' }
|
||||
});
|
||||
|
||||
console.log(`\nRole Distribution:`);
|
||||
console.log(` - Admins: ${admins}`);
|
||||
console.log(` - Members: ${members}`);
|
||||
report.push('');
|
||||
report.push('Role Distribution:');
|
||||
report.push(` - Admins: ${admins}`);
|
||||
report.push(` - Members: ${members}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Migration failed:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
await sequelize.close();
|
||||
if (report.length > 0) {
|
||||
process.stdout.write(`${report.join('\n')}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,15 +9,15 @@ import sequelize from '../database.js';
|
||||
*/
|
||||
|
||||
async function quickFixOwners() {
|
||||
console.log('Quick Fix: Setting club owners...\n');
|
||||
const report = [];
|
||||
report.push('Quick Fix: Setting club owners...');
|
||||
|
||||
try {
|
||||
const clubs = await Club.findAll();
|
||||
|
||||
console.log(`Found ${clubs.length} club(s)\n`);
|
||||
report.push(`Found ${clubs.length} club(s)`);
|
||||
|
||||
for (const club of clubs) {
|
||||
console.log(`Club: ${club.name} (ID: ${club.id})`);
|
||||
report.push(`Club: ${club.name} (ID: ${club.id})`);
|
||||
|
||||
// Find all approved members, ordered by creation date
|
||||
const userClubs = await UserClub.findAll({
|
||||
@@ -34,7 +34,7 @@ async function quickFixOwners() {
|
||||
});
|
||||
|
||||
if (userClubs.length === 0) {
|
||||
console.log(' ⚠️ No approved members\n');
|
||||
report.push(' ⚠️ No approved members');
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -58,21 +58,20 @@ async function quickFixOwners() {
|
||||
role: 'admin'
|
||||
});
|
||||
|
||||
console.log(` ✅ Owner: ${firstUserClub.user.email}`);
|
||||
report.push(` ✅ Owner: ${firstUserClub.user.email}`);
|
||||
|
||||
// Set role for other members if not set
|
||||
for (let i = 1; i < userClubs.length; i++) {
|
||||
const uc = userClubs[i];
|
||||
if (!uc.role) {
|
||||
await uc.update({ role: 'member' });
|
||||
console.log(` 👤 Member: ${uc.user.email}`);
|
||||
report.push(` 👤 Member: ${uc.user.email}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('');
|
||||
report.push('');
|
||||
}
|
||||
|
||||
console.log('✅ Quick fix completed!\n');
|
||||
report.push('✅ Quick fix completed!');
|
||||
|
||||
// Show all owners
|
||||
const owners = await UserClub.findAll({
|
||||
@@ -82,10 +81,9 @@ async function quickFixOwners() {
|
||||
{ model: Club, as: 'club', attributes: ['name'] }
|
||||
]
|
||||
});
|
||||
|
||||
console.log('Current Club Owners:');
|
||||
report.push('Current Club Owners:');
|
||||
for (const owner of owners) {
|
||||
console.log(` 📍 ${owner.club.name}: ${owner.user.email} (role: ${owner.role})`);
|
||||
report.push(` 📍 ${owner.club.name}: ${owner.user.email} (role: ${owner.role})`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -93,6 +91,9 @@ async function quickFixOwners() {
|
||||
throw error;
|
||||
} finally {
|
||||
await sequelize.close();
|
||||
if (report.length > 0) {
|
||||
process.stdout.write(`${report.join('\n')}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user