Recently I got a task to evaluate an existing software for technical fitness. Although the technical quality was in focus, it was still important for me to take a look from the user's perspective as well. To run the software I needed quickly a PostgreSQL server.

Usually I have PostgreSQL already running on my development machine, but for this test I used a fresh virtual machine. I used NixOS in the virtual machine, so one option would have been to activate the PostgreSQL service on the system. Another typical approach would be to use a container to provide a database service.

Usually I don't question these approaches and just pick one and go ahead. This time I was curios what it would mean to manually set up the database service.

Manual setup of PostgreSQL in five lines

It turns out that setting up PostgreSQL for a simple development environment is very easy. Here are the commands:

nix-shell -p postgresql
export PGDATA=~/tmp/pgdata
pg_ctl start
createdb myproject

To my surprise that's all it needs to get up and running for quick experiments.

nix-shell -p postgresql

This is an on-demand installation of postgresql via Nix the package manager. It will go and get postgresql and afterwards dump you into a shell where the binaries are already in the path.

All this happens without cluttering with your system.

export PGDATA
It turns out that telling PostgreSQL where its home resides is enough to make everything work. All other files are installed relative to this path by default.
This command will initialize the database cluster. This means it will go and create the directory structure where PGDATA points it to.
pg_ctl start
Starts the database server in the background. I find this useful, so that I can later run my project in the same shell.
createdb myproject
And finally this will create an empty database to point your project to.

Connecting to the database

In my case I was using a software which was written in Python with the Pyramid framework. It was using SQLAlchemy to connect to the database.

Things are straight forward as long as PGDATA points to the right place. As long as I just specify that I want to talk to PostgreSQL and my database name, things will go through a socket file and no special setup is needed for authentication etc.

Here is the database configuration:

sqlalchemy.url = postgresql:///myproject


I am quite surprised how simple the setup actually is. It's a fair alternative to setting up a system service or to try to make Docker the hammer for everything that looks somewhat like a nail. This approach is certainly a new citizen in my personal toolbox as a developer.


comments powered by Disqus