Languages
[Edit]
EN

Node.js - PostgreSQL - sizes of all databases

0 points
Created by:
Dirask Admin - MR
1340

In this article, we would like to show you how to check the sizes of all databases 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();

Result: 

┌─────────┬─────────────────┬───────────────┐
│ (index) │  database_name  │ database_size │
├─────────┼─────────────────┼───────────────┤
│    0    │   'postgres'    │   '7965 kB'   │
│    1    │    'dirask'     │   '8245 kB'   │
│    2    │   'template1'   │   '7753 kB'   │
│    3    │   'template0'   │   '7753 kB'   │
│    4    │ 'postgres_test' │   '7753 kB'   │
│    5    │  'my_database'  │   '7753 kB'   │
│    6    │  'm_database'   │   '7753 kB'   │
│    7    │  'database3'    │   '7753 kB'   │
│    8    │ 'my_datadbase'  │   '7753 kB'   │
└─────────┴─────────────────┴───────────────┘

Native SQL query (used in the above example):

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";

Node.js - PostgreSQL - Problems

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