feat(week1): complete foundation - schema, migrations, enhanced SQL, sanitizer

This commit is contained in:
cawcenter
2025-12-14 22:17:23 -05:00
parent 209a7e65ae
commit ffd7033501
7 changed files with 1047 additions and 1 deletions

View File

@@ -1,4 +1,4 @@
import { query } from '../db';
import { query, pool } from '../db';
export const MECHANIC_OPS = {
// 1. DIAGNOSTICS (The Stethoscope)
@@ -53,3 +53,65 @@ export const MECHANIC_OPS = {
}
}
};
/**
* Kill stuck database locks/queries
* Returns number of processes terminated
*/
export async function killLocks(): Promise<number> {
const result = await query(`
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'active'
AND query_start < NOW() - INTERVAL '30 seconds'
AND pid <> pg_backend_pid()
`);
console.log(`🔧 [Mechanic] Killed ${result.rowCount} stuck processes`);
return result.rowCount || 0;
}
/**
* Run VACUUM ANALYZE on a table or entire database
* NOTE: Must be run outside of transaction
*/
export async function vacuumAnalyze(tableName?: string): Promise<void> {
const client = await pool.connect();
try {
const table = tableName || '';
const sql = table ? `VACUUM ANALYZE ${table}` : 'VACUUM ANALYZE';
console.log(`🔧 [Mechanic] Running: ${sql}`);
await client.query(sql);
console.log(`✅ [Mechanic] Vacuum complete`);
} finally {
client.release();
}
}
/**
* Get table bloat statistics
*/
export async function getTableBloat(): Promise<any[]> {
const result = await query(`
SELECT
schemaname,
tablename,
pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size,
n_dead_tup as dead_rows,
n_live_tup as live_rows,
CASE
WHEN n_live_tup > 0
THEN round(100.0 * n_dead_tup / n_live_tup, 2)
ELSE 0
END as bloat_pct
FROM pg_stat_user_tables
WHERE n_dead_tup > 0
ORDER BY n_dead_tup DESC
LIMIT 20
`);
return result.rows;
}