Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions modules/postgres/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,8 +295,11 @@ func (c *PostgresContainer) Restore(ctx context.Context, opts ...SnapshotOption)

// execute the commands to restore the snapshot, in order
return c.execCommandsSQL(ctx,
// Drop the entire database by connecting to the postgres global database
fmt.Sprintf(`DROP DATABASE "%s" with (FORCE)`, c.dbName),
// 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 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),
)
Expand Down
Loading