Skip to content

cronn/postgres-snapshot-util

Repository files navigation

CI Maven Central Apache 2.0 codecov Valid Gradle Wrapper

Snapshot Utilities for PostgreSQL

This library provides Java wrappers to run pg_dump and pg_restore on platforms that do not have this binary installed. We build on top of Testcontainers to spin-up a temporary Docker container that executes the command.

Usage

Add the following Maven dependency to your project:

<dependency>
    <groupId>de.cronn</groupId>
    <artifactId>postgres-snapshot-util</artifactId>
    <version>1.2</version>
</dependency>

Simple Schema Dump

String jdbcUrl = "jdbc:postgresql://localhost/my-db";
String schemaDump = PostgresDump.dumpToString(jdbcUrl, "user", "password",
                                              PostgresDumpOption.NO_COMMENTS,
                                              PostgresDumpOption.SCHEMA_ONLY);

Dump and Restore

Path dumpFile = Path.of("/path/to/dump.tar");
String jdbcUrl = "jdbc:postgresql://localhost/my-db";
PostgresDump.dumpToFile(dumpFile, jdbcUrl, "user", "pass", PostgresDumpFormat.TAR);

PostgresRestore.restoreFromFile(dumpFile, jdbcUrl, "user", "pass",
                                PostgresRestoreOption.CLEAN,
                                PostgresRestoreOption.EXIT_ON_ERROR,
                                PostgresRestoreOption.SINGLE_TRANSACTION);

Use Cases

Integration / Regression Test

PostgresDump was designed to be used in a JUnit (regression) tests to dump and compare the actual database schema of an application in cases where the schema is managed by a library/framework such as Liquibase. We recommend to use our validation-file-assertions library to write such a test.

Full example:

@SpringBootTest
@Testcontainers
class SchemaTest implements JUnit5ValidationFileAssertions {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17.0");

    @Test
    void schemaExport() {
        String schema = PostgresDump.dumpToString(postgres.getJdbcUrl(),
                                                  postgres.getUsername(),
                                                  postgres.getPassword(),
                                                  PostgresDumpOption.SCHEMA_ONLY);
        assertWithFile(schema);
    }
}

Requirements

  • Java 17+