back       next

PostgreSQL

PostgreSQL role based password authentication

To manage/setup role based password authentication for postgresql database.

Modify "/var/lib/pgsql/data/pg_hba.conf" and include:

host    samerole         all         127.0.0.1/32         md5

Save the below script and run:

./db_setup.sh <DBNAME> <DBMAINUSER> <DBMAINUSERPASS> create

#!/bin/bash
# db_setup.sh

USAGE="Usage: $0 <DBNAME> <DBMAINUSER> <DBMAINUSERPASS> <create|drop>"
DBNAME=${1?"$USAGE"}
DBMAINUSER=${2?"$USAGE"}
DBMAINUSERPASS=${3?"$USAGE"}

# Create new database + main user
#
create_db_and_mainuser() {
psql -U postgres template1 -f - <<EOT

CREATE ROLE ${DBNAME} NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOLOGIN;
CREATE ROLE ${DBMAINUSER} NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT LOGIN ENCRYPTED PASSWORD '${DBMAINUSERPASS}';
GRANT ${DBNAME} TO ${DBMAINUSER};
CREATE DATABASE ${DBNAME} WITH OWNER=${DBMAINUSER};

EOT
}

# Remove database + main user
#
drop_db_and_mainuser() {
psql -U postgres template1 -f - <<EOT

-- TERMINATE CONNECTIONS OF ALL USERS CONNECTED TO <DBNAME>
DROP DATABASE ${DBNAME};
DROP ROLE ${DBMAINUSER};
DROP ROLE ${DBNAME};

EOT
}

# Main
case "$4" in
  create)
    create_db_and_mainuser
    ;;
  drop)
    drop_db_and_mainuser
    ;;
  *)
    echo $USAGE
    exit 1
    ;;
esac

exit 0

You should now be able to connect using:

psql -U <DBMAINUSER> -d <DBNAME>  -h 127.0.0.1

Optimize PostgreSQL Database Size

Recently, I noticed that the postgresql database partition had been filled up. The general advice is to export data, drop and recreate database and import the data back in, since this would save a lot of time and also reduce the database size comparatively.

Reference: optimize postgresql database size.

Not too sure, if I wanted to go the dump and restore route, so decided to vacuum and reindex instead.

To my surprise, I did regain about 70% of space running the full vacuum and reindexing the database.

  • Full vacuum reduced the database size from 8GB to 4GB.
    vacuumdb -afzv | tee /tmp/vacuumdb.log

  • Reindex then reduced further to 2.5GB.
    reindexdb -a | tee /tmp/reindexdb.log

  • Total of 5.5GB space reduced with a full vacuum and reindex of the database.
  • Check the vacuumdb.log for database optimization notices.
  • It is also advised to reindex prior to vacuuming to further save on vacuum time.

PostgreSQL 8.3 install on CentOS

# wget http://yum.pgsqlrpms.org/reporpms/8.3/pgdg-centos-8.3-6.noarch.rpm
# rpm -Uvh pgdg-centos-8.3-6.noarch.rpm
# yum install postgresql-server
# service postgresql initdb
# service postgresql start

PostgreSQL QuickStart/Reference Commands...

Since I don't use PostgreSQL as often as MySQL, I tend to forget simple commands for administering the database. Hopefully these notes will help as reference when working with PostgreSQL:

Syndicate content