import { config } from "dotenv";
config();
import { Client } from "pg";

async function main() {
  const c = new Client({ connectionString: process.env.DATABASE_URL });
  await c.connect();

  const r = await c.query(`
    SELECT count(*) as active,
      (SELECT setting::int FROM pg_settings WHERE name='max_connections') as max_conn
    FROM pg_stat_activity
  `);
  console.log("active connections:", r.rows[0]?.active, "/ max:", r.rows[0]?.max_conn);

  const killed = await c.query(`
    SELECT pg_terminate_backend(pid)
    FROM pg_stat_activity
    WHERE state = 'idle'
      AND pid <> pg_backend_pid()
      AND datname = current_database()
  `);
  console.log("killed idle connections:", killed.rowCount);

  await c.end();
}

main().catch(console.error);
