At a a project I am heavily relying on PostgreSQL in the unit tests. This works fine but creating and dropping databases takes quite a while which goes against the purpose of unit tests. One simple solution to this is to run PostgreSQL in a RAM disk which will make IO-heavy operations a snap.

Setup

The way I suggest works simply by

  1. Creating a RAM disk
  2. Copying the contents of the PostgreSQL directory to the RAM disk
  3. Mounting the RAM disk over the PostgreSQL directory

This has the clear drawback that there is no write-back of any changed data. However, as I need the data only during testing this is acceptable.

Alternatives

Unfortunately PostgreSQL does not support RAM-based tables otherwise this would be a much cleaner solution. Another solution would be to create a new cluster directly in the RAM disk (using pg_createcluster). The drawback with this method is that the configuration and possibly already existing DB structures are not preserved.

Mount script

This was hacked together in a few minutes but “it works for me”™ using Ubuntu 10.10.

sudo /etc/init.d/postgresql stop
TMPDIR=/tmp/tmpfs; # the actual mount point for the tmpfs
MOUNTPOINT=/var/lib/postgresql/;
[ -d $TMPDIR ] || mkdir $TMPDIR;
sudo mount -t tmpfs -o size=512M,nr_inodes=10k,mode=0777 tmpfs $TMPDIR;
sudo rsync --archive $MOUNTPOINT/ $TMPDIR/;
sudo mount -o bind $TMPDIR $MOUNTPOINT;
sudo /etc/init.d/postgresql start