Languages

Node.js - Postgres - how to check sizes of all databases?

0 points

How to get the sizes of all Postgres databases in Node.js?

1 answer
3 points
Answered by:
Dirask Admin - Marvin
1940

I found a solution:

In SQL: 

SELECT 
    "pg_db"."datname" AS "database_name",  
    pg_size_pretty(pg_database_size("pg_db".datname)) AS "database_size"
FROM "pg_database" AS "pg_db";

Practical example in Node.js:

const { Client } = require('pg');

const client = new Client({
    host: '127.0.0.1',
    user: 'postgres',
    password: 'password',
    port: 5432,
});

const getSizesOfAllDatabases = async () => {
    const query = `
        SELECT 
            "pg_db"."datname" AS "database_name",
            pg_size_pretty(pg_database_size("pg_db"."datname")) AS "database_size"
        FROM "pg_database" AS "pg_db";`;
    try {
        await client.connect(); // gets connection
        const { rows } = await client.query(query); // sends query
        console.table(rows);
    } catch (error) {
        console.error(error.stack);
        return false;
    } finally {
        await client.end();     // closes connection
    }
};

getSizesOfAllDatabases();

For better understanding, I also made an article:

0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join