EN
Node.js / PostgreSQL - list sizes of databases
3 points
In this article, we would like to show you how to list the sizes of PostgreSQL databases using Node.js.
Quick solution:
xxxxxxxxxx
1
const { Client } = require('pg');
2
β
3
const client = new Client({
4
host: '127.0.0.1',
5
user: 'postgres',
6
password: 'password',
7
port: 5432,
8
});
9
β
10
const printDatabasesSizes = async () => {
11
const query = `
12
SELECT
13
"d"."datname" AS "database_name",
14
pg_size_pretty(pg_database_size("d"."datname")) AS "database_size"
15
FROM "pg_database" AS "d"
16
`;
17
try {
18
await client.connect(); // creates connection
19
const { rows } = await client.query(query); // sends query
20
console.table(rows);
21
} catch (error) {
22
console.error(error.stack);
23
return false;
24
} finally {
25
await client.end(); // closes connection
26
}
27
};
28
β
29
printDatabasesSizes();
Example result:
xxxxxxxxxx
1
βββββββββββ¬ββββββββββββββββββ¬ββββββββββββββββ
2
β (index) β database_name β database_size β
3
βββββββββββΌββββββββββββββββββΌββββββββββββββββ€
4
β 0 β 'postgres' β '7965 kB' β
5
β 1 β 'dirask' β '8245 kB' β
6
β 2 β 'template1' β '7753 kB' β
7
β 3 β 'template0' β '7753 kB' β
8
β 4 β 'postgres_test' β '7753 kB' β
9
β 5 β 'my_database' β '7753 kB' β
10
β 6 β 'm_database' β '7753 kB' β
11
β 7 β 'database3' β '7753 kB' β
12
β 8 β 'my_datadbase' β '7753 kB' β
13
βββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββ
Native SQL query (used in the above example):
xxxxxxxxxx
1
SELECT
2
"d"."datname" AS "database_name",
3
pg_size_pretty(pg_database_size("d".datname)) AS "database_size"
4
FROM "pg_database" AS "d";