From c521dc0f254554e3facca8b6931c2acc039216bd Mon Sep 17 00:00:00 2001 From: Gerd Aschemann Date: Tue, 19 Aug 2025 16:30:46 +0200 Subject: [PATCH 1/2] #3263 fix: Terminate existing connections to snapshot DB --- modules/postgres/postgres.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/postgres/postgres.go b/modules/postgres/postgres.go index f03adc7e16..c1a5ede30d 100644 --- a/modules/postgres/postgres.go +++ b/modules/postgres/postgres.go @@ -295,6 +295,9 @@ func (c *PostgresContainer) Restore(ctx context.Context, opts ...SnapshotOption) // execute the commands to restore the snapshot, in order return c.execCommandsSQL(ctx, + // Terminate all connections to the template database explicitly as the forced drop below will sometimes + // not terminate them and then fail to drop the database. + fmt.Sprintf(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '%s' AND pid <> pg_backend_pid()`, snapshotName), // Drop the entire database by connecting to the postgres global database fmt.Sprintf(`DROP DATABASE "%s" with (FORCE)`, c.dbName), // Then restore the previous snapshot From 240a2eecb0b3db64c4ebfcc598c6a1cb666cbc83 Mon Sep 17 00:00:00 2001 From: Gerd Aschemann Date: Tue, 19 Aug 2025 16:38:54 +0200 Subject: [PATCH 2/2] #3263 fix: Drop existing DB only if it exists --- modules/postgres/postgres.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/postgres/postgres.go b/modules/postgres/postgres.go index c1a5ede30d..960e2ce398 100644 --- a/modules/postgres/postgres.go +++ b/modules/postgres/postgres.go @@ -298,8 +298,8 @@ func (c *PostgresContainer) Restore(ctx context.Context, opts ...SnapshotOption) // Terminate all connections to the template database explicitly as the forced drop below will sometimes // not terminate them and then fail to drop the database. fmt.Sprintf(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '%s' AND pid <> pg_backend_pid()`, snapshotName), - // Drop the entire database by connecting to the postgres global database - fmt.Sprintf(`DROP DATABASE "%s" with (FORCE)`, c.dbName), + // Drop the database if it exists + fmt.Sprintf(`DROP DATABASE IF EXISTS "%s" with (FORCE)`, c.dbName), // Then restore the previous snapshot fmt.Sprintf(`CREATE DATABASE "%s" WITH TEMPLATE "%s" OWNER "%s"`, c.dbName, snapshotName, c.user), )