Search code examples
postgresqlunit-testingpostgresql-performance

Running PostgreSQL in memory only


I want to run a small PostgreSQL database which runs in memory only, for each unit test I write. For instance:

@Before
void setUp() {
    String port = runPostgresOnRandomPort();
    connectTo("postgres://localhost:"+port+"/in_memory_db");
    // ...
}

Ideally I'll have a single postgres executable checked into the version control, which the unit test will use.

Something like HSQL, but for postgres. How can I do that?

Were can I get such a Postgres version? How can I instruct it not to use the disk?


Solution

  • This is not possible with Postgres. It does not offer an in-process/in-memory engine like HSQLDB or MySQL.

    If you want to create a self-contained environment you can put the Postgres binaries into SVN (but it's more than just a single executable).

    You will need to run initdb to setup your test database before you can do anything with this. This can be done from a batch file or by using Runtime.exec(). But note that initdb is not something that is fast. You will definitely not want to run that for each test. You might get away running this before your test-suite though.

    However while this can be done, I'd recommend to have a dedicated Postgres installation where you simply recreate your test database before running your tests.

    You can re-create the test-database by using a template database which makes creating it quite fast (a lot faster than running initdb for each test run)