Skip to content

Commit 9c6d44d

Browse files
fix: resolve DropTestDatabase and CreateTestDatabase concurrency issue
1 parent aaf7d50 commit 9c6d44d

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

template_manager.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -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.
219219
func (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

Comments
 (0)