Java basics
pgmem for the JVM has a core client (io.github.shibukawa.pgmem:pgmem), testing modules (pgmem-junit5, pgmem-spring, and pgmem-micronaut), and a platform-specific binary (pgmem-native). The client has no third-party runtime dependencies; bring your JDBC driver.
Dependencies
Section titled “Dependencies”val pgmemOs = System.getProperty("os.name").lowercase()val pgmemArch = System.getProperty("os.arch").lowercase()val pgmemPlatform = when { pgmemOs.contains("mac") || pgmemOs.contains("darwin") -> "darwin" pgmemOs.contains("win") -> "windows" pgmemOs.contains("linux") -> "linux" else -> error("Unsupported OS: $pgmemOs; use PGMEM_BINARY")}val pgmemCpu = when (pgmemArch) { "amd64", "x86_64" -> "x86_64" "aarch64", "arm64" -> "arm64" else -> error("Unsupported architecture: $pgmemArch; use PGMEM_BINARY")}val pgmemNative = "$pgmemPlatform-$pgmemCpu"
dependencies { testImplementation("io.github.shibukawa.pgmem:pgmem-junit5:1.18.0") // pulls in io.github.shibukawa.pgmem:pgmem testRuntimeOnly("io.github.shibukawa.pgmem:pgmem-native:1.18.0:$pgmemNative") // the binary for your platform testRuntimeOnly("org.postgresql:postgresql:42.7.7") testImplementation(platform("org.junit:junit-bom:5.14.0")) testImplementation("org.junit.jupiter:junit-jupiter") testRuntimeOnly("org.junit.platform:junit-platform-launcher")}
tasks.test { useJUnitPlatform()}def pgmemOs = System.getProperty('os.name').toLowerCase()def pgmemArch = System.getProperty('os.arch').toLowerCase()def pgmemPlatform = pgmemOs.contains('mac') || pgmemOs.contains('darwin') ? 'darwin' : pgmemOs.contains('win') ? 'windows' : pgmemOs.contains('linux') ? 'linux' : nulldef pgmemCpu = ['amd64', 'x86_64'].contains(pgmemArch) ? 'x86_64' : ['aarch64', 'arm64'].contains(pgmemArch) ? 'arm64' : nullif (!pgmemPlatform || !pgmemCpu) throw new GradleException('Unsupported host; use PGMEM_BINARY')def pgmemNative = "${pgmemPlatform}-${pgmemCpu}"
dependencies { testImplementation 'io.github.shibukawa.pgmem:pgmem-junit5:1.18.0' // pulls in io.github.shibukawa.pgmem:pgmem testRuntimeOnly "io.github.shibukawa.pgmem:pgmem-native:1.18.0:${pgmemNative}" // the binary for your platform testRuntimeOnly 'org.postgresql:postgresql:42.7.7' testImplementation platform('org.junit:junit-bom:5.14.0') testImplementation 'org.junit.jupiter:junit-jupiter' testRuntimeOnly 'org.junit.platform:junit-platform-launcher'}
test { useJUnitPlatform()}<dependencies> <dependency> <groupId>io.github.shibukawa.pgmem</groupId> <artifactId>pgmem-junit5</artifactId> <version>1.18.0</version> <scope>test</scope> </dependency> <dependency> <groupId>io.github.shibukawa.pgmem</groupId> <artifactId>pgmem-native</artifactId> <version>1.18.0</version> <classifier>${pgmem.native.classifier}</classifier> <scope>test</scope> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.7.7</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>5.14.0</version> <scope>test</scope> </dependency></dependencies>The classifiers are linux-x86_64, linux-arm64, darwin-arm64, windows-x86_64 and windows-arm64. When a build runs on several platforms, pick one per platform with Maven profiles or a Gradle OS detection plugin rather than depending on all five. The binary is extracted once into ~/.cache/pgmem/<version>/. Java 17 or newer.
The Gradle examples select the classifier from the build host. With Maven, pass it explicitly, for example mvn -Dpgmem.native.classifier=linux-x86_64 test, or add the profiles below to select it automatically on multiple hosts. Intel Macs have no native artifact; omit the native dependency and use a local build through PGMEM_BINARY.
If the existing Maven build does not already run JUnit 5 tests, add this build configuration as well.
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.14.0</version> <configuration><release>17</release></configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.5.4</version> </plugin> </plugins></build>Maven profiles
<profiles> <profile> <id>pgmem-linux-amd64</id> <activation><os><name>Linux</name><arch>amd64</arch></os></activation> <properties><pgmem.native.classifier>linux-x86_64</pgmem.native.classifier></properties> </profile> <profile> <id>pgmem-linux-x86_64</id> <activation><os><name>Linux</name><arch>x86_64</arch></os></activation> <properties><pgmem.native.classifier>linux-x86_64</pgmem.native.classifier></properties> </profile> <profile> <id>pgmem-linux-aarch64</id> <activation><os><name>Linux</name><arch>aarch64</arch></os></activation> <properties><pgmem.native.classifier>linux-arm64</pgmem.native.classifier></properties> </profile> <profile> <id>pgmem-linux-arm64</id> <activation><os><name>Linux</name><arch>arm64</arch></os></activation> <properties><pgmem.native.classifier>linux-arm64</pgmem.native.classifier></properties> </profile> <profile> <id>pgmem-darwin-aarch64</id> <activation><os><family>mac</family><arch>aarch64</arch></os></activation> <properties><pgmem.native.classifier>darwin-arm64</pgmem.native.classifier></properties> </profile> <profile> <id>pgmem-darwin-arm64</id> <activation><os><family>mac</family><arch>arm64</arch></os></activation> <properties><pgmem.native.classifier>darwin-arm64</pgmem.native.classifier></properties> </profile> <profile> <id>pgmem-windows-amd64</id> <activation><os><family>windows</family><arch>amd64</arch></os></activation> <properties><pgmem.native.classifier>windows-x86_64</pgmem.native.classifier></properties> </profile> <profile> <id>pgmem-windows-x86_64</id> <activation><os><family>windows</family><arch>x86_64</arch></os></activation> <properties><pgmem.native.classifier>windows-x86_64</pgmem.native.classifier></properties> </profile> <profile> <id>pgmem-windows-aarch64</id> <activation><os><family>windows</family><arch>aarch64</arch></os></activation> <properties><pgmem.native.classifier>windows-arm64</pgmem.native.classifier></properties> </profile> <profile> <id>pgmem-windows-arm64</id> <activation><os><family>windows</family><arch>arm64</arch></os></activation> <properties><pgmem.native.classifier>windows-arm64</pgmem.native.classifier></properties> </profile></profiles>The basic flow
Section titled “The basic flow”-
Start the process.
PgmemisAutoCloseable; closing it stops every server.try (Pgmem pg = Pgmem.builder().database("app").start()) {Server template = pg.template();System.out.println(template.jdbcUrl()); // jdbc:postgresql://127.0.0.1:54321/app?user=postgres&sslmode=disable}Pgmem.builder().database("app").start().use { pg ->val template = pg.template()println(template.jdbcUrl())}The builder also takes
user(...),param("shared_buffers", "128MB"),log(true)andbinary(path). -
Register the schema with a migration tool. See migration tools.
-
Load seed data. See seed data.
-
Use it through JDBC.
jdbcUrl()carries the user andsslmode, anddataSource()returns ajavax.sql.DataSource.try (Connection conn = DriverManager.getConnection(template.jdbcUrl());PreparedStatement ps = conn.prepareStatement("SELECT name FROM users WHERE id = ?")) {ps.setLong(1, 1);try (ResultSet rs = ps.executeQuery()) {rs.next();String name = rs.getString(1);}}DriverManager.getConnection(template.jdbcUrl()).use { conn ->conn.prepareStatement("SELECT name FROM users WHERE id = ?").use { ps ->ps.setLong(1, 1)ps.executeQuery().use { rs -> rs.next(); println(rs.getString(1)) }}}A HikariCP pool on the URL works too; every connection gets its own backend process.
Migration tools
Section titled “Migration tools”String schema = Files.readString(Path.of("src/test/resources/schema.sql"));try (Connection conn = DriverManager.getConnection(template.jdbcUrl()); Statement st = conn.createStatement()) { st.execute(schema);}Flyway.configure() .dataSource(template.jdbcUrl(), template.user(), null) .locations("classpath:db/migration") .load() .migrate();Flyway 10 and later also need org.flywaydb:flyway-database-postgresql on the test classpath.
try (Connection conn = DriverManager.getConnection(template.jdbcUrl())) { Database db = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(new JdbcConnection(conn)); new CommandScope("update") .addArgumentValue("database", db) .addArgumentValue("changelogFile", "db/changelog/db.changelog-master.yaml") .execute();}Seed data
Section titled “Seed data”<dataset> <users id="1" name="Frank" email="frank@example.com"/> <users id="2" name="Grace" email="grace@example.com"/> <orders id="1" user_id="1" amount="1200"/></dataset>IDatabaseTester tester = new JdbcDatabaseTester( "org.postgresql.Driver", template.jdbcUrl(), template.user(), "");tester.setDataSet(new FlatXmlDataSetBuilder() .build(getClass().getResourceAsStream("/seed.xml")));tester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);tester.onSetup();try (Connection conn = DriverManager.getConnection(template.jdbcUrl()); Statement st = conn.createStatement()) { st.execute(Files.readString(Path.of("src/test/resources/seed.sql")));}try (Connection conn = DriverManager.getConnection(template.jdbcUrl())) { CopyManager copy = conn.unwrap(PGConnection.class).getCopyAPI(); copy.copyIn("COPY users (id, name, email) FROM STDIN (FORMAT csv)", new StringReader("1,Frank,frank@example.com\n2,Grace,grace@example.com\n"));}Snapshot and fork by hand
Section titled “Snapshot and fork by hand”try (Pgmem pg = Pgmem.builder().database("app").start()) { migrate(pg.template().jdbcUrl()); Snapshot snap = pg.template().snapshot(); // waits for open transactions, 30 s try (Fork fork = snap.fork()) { // a private copy DataSource ds = fork.dataSource(); // ... }}Commit or close every connection to the template before snapshot(). The JUnit 5 extension on the next page wires this into the test lifecycle.