Skip to content

Commit 901b0b9

Browse files
authored
fix(postgres): snapshot restore (#3264)
Terminate existing connections to snapshot DB. Drop existing DB only if it exists.
1 parent c100f88 commit 901b0b9

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

modules/postgres/postgres.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -295,8 +295,11 @@ func (c *PostgresContainer) Restore(ctx context.Context, opts ...SnapshotOption)
295295

296296
// execute the commands to restore the snapshot, in order
297297
return c.execCommandsSQL(ctx,
298-
// Drop the entire database by connecting to the postgres global database
299-
fmt.Sprintf(`DROP DATABASE "%s" with (FORCE)`, c.dbName),
298+
// Terminate all connections to the template database explicitly as the forced drop below will sometimes
299+
// not terminate them and then fail to drop the database.
300+
fmt.Sprintf(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '%s' AND pid <> pg_backend_pid()`, snapshotName),
301+
// Drop the database if it exists
302+
fmt.Sprintf(`DROP DATABASE IF EXISTS "%s" with (FORCE)`, c.dbName),
300303
// Then restore the previous snapshot
301304
fmt.Sprintf(`CREATE DATABASE "%s" WITH TEMPLATE "%s" OWNER "%s"`, c.dbName, snapshotName, c.user),
302305
)

0 commit comments

Comments
 (0)