@@ -217,28 +217,31 @@ func (tm *TemplateManager) CreateTestDatabase(ctx context.Context, testDBName ..
217217//
218218// The caller is expected to call Initialize() before using this method.
219219func (tm * TemplateManager ) DropTestDatabase (ctx context.Context , dbName string ) error {
220- // Connect to template database for DROP operations.
221- // This is preferred to follow the least privilege principle.
222- templateConn , err := tm .provider .Connect (ctx , tm .templateName )
220+ // Connect to admin database for DROP operations.
221+ // Even though we could connect to the template database,
222+ // we cannot do this as the user can call CreateTestDatabase
223+ // at the same time and creating test databases from template
224+ // requires no active connections to the template.
225+ adminConn , err := tm .provider .Connect (ctx , tm .adminDBName )
223226 if err != nil {
224- return fmt .Errorf ("failed to connect to template database: %w" , err )
227+ return fmt .Errorf ("failed to connect to admin database: %w" , err )
225228 }
226- defer templateConn .Close ()
229+ defer adminConn .Close ()
227230
228231 // Terminate active connections to the database.
229232 terminateQuery := `
230233 SELECT pg_terminate_backend(pid)
231234 FROM pg_stat_activity
232235 WHERE datname = $1 AND pid <> pg_backend_pid()
233236 `
234- _ , err = templateConn .ExecContext (ctx , terminateQuery , dbName )
237+ _ , err = adminConn .ExecContext (ctx , terminateQuery , dbName )
235238 if err != nil {
236239 return fmt .Errorf ("failed to terminate connections to database %q: %w" , dbName , err )
237240 }
238241
239242 // Drop the database.
240243 dropQuery := fmt .Sprintf ("DROP DATABASE %s" , formatters .QuoteIdentifier (dbName ))
241- if _ , err := templateConn .ExecContext (ctx , dropQuery ); err != nil {
244+ if _ , err := adminConn .ExecContext (ctx , dropQuery ); err != nil {
242245 return fmt .Errorf ("failed to drop database %s: %w" , dbName , err )
243246 }
244247
0 commit comments