Languages
[Edit]
EN

Node.js - PostgreSQL - sizes of all databases

0 points
Created by:
Lillie-Rose-Finnegan
309

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