#!/bin/sh
# @(#) list PostgreSQL databases
# too trivial to claim any copyright, since the query was stolen from psql(1)
# written in 2008 by Dirk Jagdmann <doj@cubic.org>

usage="usage: listdb [-H host]\
\n-H specifies the hostname of the machine on wich the server is running"

if [ -z "$PGDATABASE" ] ; then
   PGDATABASE=template1
fi

HOST=""

while getopts "H:h" options; do
  case $options in
    H ) HOST="-h $OPTARG";;
    h ) echo -e $usage
         exit 1;;
    \? ) echo -e $usage
         exit 1;;
    * ) echo -e $usage
          exit 1;;
  esac
done

Q="SELECT d.datname as Name,
          r.rolname as Owner,
          pg_catalog.pg_encoding_to_char(d.encoding) as Encoding,
          t.spcname as Tablespace,
          pg_size_pretty(pg_database_size(d.datname)) as Size,
          pg_catalog.shobj_description(d.oid, 'pg_database') as Description
     FROM pg_catalog.pg_database d
     JOIN pg_catalog.pg_roles r ON d.datdba = r.oid
     JOIN pg_catalog.pg_tablespace t on d.dattablespace = t.oid
 ORDER BY Name"

psql $HOST -c "$Q" "$PGDATABASE"
RETURN=$?

if [ $RETURN -ne 0 ]
then
    echo "\nTry $(basename $0) -h to see help"
fi

exit $RETURN

=head1 NAME

listdb - list databases, owners, encoding, tablespace and description

=head1 SYNOPSIS

listdb [-H hostname]

=head1 OPTIONS

=over

=item -H hostname

connect to database B<hostname>

=back

=head1 ENVIRONMENT

B<PGDATABASE>, B<PGHOST>, B<PGPORT>, B<PGUSER> as described in psql(1).

=head1 SEE ALSO

\l command in psql(1)

=head1 AUTHOR

the "listdb" program: Dirk Jagdmann <doj@cubic.org>

the SQL query: authors of psql(1)

L<http://pgfoundry.org/projects/pg-toolbox/>

=cut
