Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Oneiroi/ec2a5a43fe7ebf870db8c31a74e04754 to your computer and use it in GitHub Desktop.
Save Oneiroi/ec2a5a43fe7ebf870db8c31a74e04754 to your computer and use it in GitHub Desktop.
#!/bin/bash
# "---------------------------------------------------"
# " This is a simple script for creating a query "
# " that collects data from the table pg_class "
# " for list of databases "
# "---------------------------------------------------"
if [ "$#" -eq 0 ] ;
then
echo -e "\n\tYou must enter at least one database name as an argument."
echo -e "\tArguments should be separated by spaces.\n"
exit
fi
TOPPART="## Custom query\npg_class:\n query: \"SELECT datname, "
MIDDLEPART="FROM pg_database"
BOTTOMPART="WHERE datname NOT LIKE 'template_' AND datname NOT LIKE 'postgres'\""
PROMPART=" metrics:
- datname:
usage: \"LABEL\"
description: \"Name of the database that this table is in\"
- relname:
usage: \"LABEL\"
description: \"Name of the table, index, view, etc.\"
- rows:
usage: \"GAUGE\"
decription: \"Number of rows in the table. This is only an estimate used by the planner. It is updated by VACUUM, ANALYZE, and a few DDL commands such as CREATE INDEX\"
- total:
usage: \"GAUGE\"
description: \"Total disk space used by the specified table, including all indexes and TOAST data\"
- index:
usage: \"GAUGE\"
description: \"Total disk space used by indexes attached to the specified table\"
- toast:
usage: \"GAUGE\"
description: \"Total disk space used by TOAST data attached to the specified table\"
"
while [ "$1" != "" ]; do
OBJECTS=$OBJECTS" "$1
RELNAME=$RELNAME$1".relname"
ROWS=$ROWS$1".rows"
TOTAL=$TOTAL$1".total"
INDEX=$INDEX$1".index"
TOAST=$TOAST$1".toast"
if [ $# -ne 1 ] ;
then
RELNAME=$RELNAME", "
ROWS=$ROWS", "
TOTAL=$TOTAL", "
INDEX=$INDEX", "
TOAST=$TOAST", "
else
RELNAME="COALESCE("$RELNAME") as ${RELNAME//*./}"
ROWS="COALESCE("$ROWS") as ${ROWS//*./}"
TOTAL="COALESCE("$TOTAL") as ${TOTAL//*./}"
INDEX="COALESCE("$INDEX") as ${INDEX//*./}"
TOAST="COALESCE("$TOAST",0) as ${TOAST//*./}"
fi
shift
done
echo -ne "$TOPPART"
echo -n "$RELNAME, $ROWS, $TOTAL, $INDEX, $TOAST "
echo -n "$MIDDLEPART"
for t in $OBJECTS; do
DB=$DB" LEFT OUTER JOIN dblink('dbname=$t','SELECT current_database(), relname, CAST(reltuples as BIGINT), pg_total_relation_size(oid), pg_indexes_size(oid), pg_total_relation_size(reltoastrelid) FROM pg_class') as $t(datname name, relname name, rows BIGINT, total BIGINT, index BIGINT, toast BIGINT) USING (datname)"
done
echo -n "$DB "
echo "$BOTTOMPART"
echo -e "$PROMPART"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment