- Introduced new scripts: check-connections and cleanup-connections for managing database connections. - These scripts enhance the backend's ability to monitor and maintain connection health.
56 lines
1.9 KiB
JavaScript
56 lines
1.9 KiB
JavaScript
#!/usr/bin/env node
|
|
|
|
/**
|
|
* Script zum Bereinigen von alten/idle PostgreSQL-Verbindungen
|
|
*/
|
|
|
|
import './config/loadEnv.js';
|
|
import { sequelize } from './utils/sequelize.js';
|
|
|
|
async function main() {
|
|
try {
|
|
console.log('🧹 Bereinige alte PostgreSQL-Verbindungen...\n');
|
|
|
|
// Beende idle Verbindungen, die älter als 5 Minuten sind (außer unserer eigenen)
|
|
const [result] = await sequelize.query(`
|
|
SELECT pg_terminate_backend(pid) as terminated
|
|
FROM pg_stat_activity
|
|
WHERE datname = current_database()
|
|
AND pid <> pg_backend_pid()
|
|
AND state = 'idle'
|
|
AND state_change < now() - interval '5 minutes';
|
|
`);
|
|
|
|
const terminated = result.filter(r => r.terminated).length;
|
|
console.log(`✅ ${terminated} alte idle Verbindungen wurden beendet\n`);
|
|
|
|
// Zeige verbleibende Verbindungen
|
|
const [connections] = await sequelize.query(`
|
|
SELECT
|
|
count(*) as total,
|
|
count(*) FILTER (WHERE state = 'active') as active,
|
|
count(*) FILTER (WHERE state = 'idle') as idle
|
|
FROM pg_stat_activity
|
|
WHERE datname = current_database();
|
|
`);
|
|
|
|
console.log('📊 Verbleibende Verbindungen:');
|
|
console.log(` Gesamt: ${connections[0].total}`);
|
|
console.log(` Aktiv: ${connections[0].active}`);
|
|
console.log(` Idle: ${connections[0].idle}\n`);
|
|
|
|
await sequelize.close();
|
|
process.exit(0);
|
|
|
|
} catch (error) {
|
|
console.error('❌ Fehler:', error.message);
|
|
if (error.message.includes('SUPERUSER')) {
|
|
console.error('\n💡 Tipp: Du benötigst Superuser-Rechte oder musst warten, bis Verbindungen freigegeben werden.');
|
|
console.error(' Versuche es in ein paar Minuten erneut.');
|
|
}
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
main();
|