I recently had to setup a local database for testing purposes. The last time I did that was on Mac OS. On that platform the awesome Postgres.app is available that sets up a dev database in seconds. (Seriously, if you are a developer on Mac you should check that out.)

On Linux --- and in my case NixOS -- the process is more involved unfortunately. You can't (as far as I know) just put something into your dev environment shell.nix file and expect everything to work.

Here are my steps:

Install Postgres

You can do this userwide via nix-env -i postgresql, but in my case I wanted it to only apply to one project so I put it in that project's shell.nix.

1
2
3
4
5
6
7
with import <nixpkgs> {};

mkShell {
  buildInputs = [
    postgresql
  ];
}

Setup the database

Next you have to setup the database:

1
2
3
$ initdb -D .tmp/database # Change the directory to wherever you want your data store to be
$ mkdir /run/postgresql # Postgres will try to create a pid file and complains if this folder doesn't exist
$ createdb # Create an empty database for the current user

Conclusion

In the end that wasn't too hard, but having to look up cryptic errors like FATAL: could not create lock file "/run/postgresql/.s.PGSQL.5432.lock": No such file or directory only to find out that you have to do some local filesystem and setup shenanigans isn't the nix experience. I'd like to just go: "Hey nix, give my a postgres database please." And maybe that exists, but the Postgres on Nix documentation is sparse and I was not able to find a better way.