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.
Add the following Maven dependency to your project:
<dependency>
<groupId>de.cronn</groupId>
<artifactId>postgres-snapshot-util</artifactId>
<version>1.2</version>
</dependency>
String jdbcUrl = "jdbc:postgresql://localhost/my-db";
String schemaDump = PostgresDump.dumpToString(jdbcUrl, "user", "password",
PostgresDumpOption.NO_COMMENTS,
PostgresDumpOption.SCHEMA_ONLY);
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);
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);
}
}
- Java 17+