Minimal postgres instance for testing

I have code that interacts with postgres databases through JDBC. However, for testing purposes, I just want to quickly create a new database and connect to it without having to change my global postgres installation, manage users, etc. How do people usually carry out such checks?

+8
java postgresql jdbc testing
source share
3 answers

I would find the initdb executable and use it to create a new temporary storage for the database instance writable by the current user. Since this is a test instance, use something like initdb --auth=trust --username=postgres -D /path/to/temp/datadir , so the new database is configured to accept connections without the need for passwords.

Use pg_ctl to start the server by specifying a port to override the default value in the generated postgresql.conf and avoid conflicts.

Connect to the new database cluster and do any work. First you need to log in as the postgres user and run any required CREATE USER and CREATE DATABASE commands before transferring control of your test code.

Finally, use pg_ctl to stop it and finally delete the data directory.

All you need is initdb and pg_ctl in PATH and a helper class for managing the server.

Cm:

+7
source share

There are several libraries that create temporary Postgres instances for testing:

All of them are designed to automatically close and delete a temporary database. Here's how you could use pg_tmp(1) to create a minimal Postgres instance from Java:

 import java.io.*; import java.sql.*; public class test_pg { public static void main(String args[]) { try { Process p = Runtime.getRuntime().exec("pg_tmp -t"); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); String pg_uri = "jdbc:" + input.readLine(); input.close(); System.out.println("Using " + pg_uri); Connection conn = DriverManager.getConnection(pg_uri); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select now()"); while(rs.next()) { System.out.print(rs.getString(1)); } } catch(IOException | SQLException e) { e.printStackTrace(); } } } 
+4
source share

You can install a Postgres instance in your home directory, working on a different port and under your user. See here for example:

http://www.bacula.org/manuals/en/catalog/catalog/Installi_Configur_PostgreS.html

You can also check your Heroku code, depending on what it is. They give you a small virtual Postgres database for free.

0
source share

All Articles