From fd4cd15b8030942e3c51f99a86527dfa3879125c Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 22 Oct 2019 11:35:14 +0200 Subject: [PATCH] Add SELECT 1 check to Exists/CanConnect checks Fixes #18330 --- .../Internal/SqlServerDatabaseCreator.cs | 52 +++++++++++++++---- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs index 7fdfbd28cc1..ac1efcc6322 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs @@ -183,13 +183,21 @@ private bool Exists(bool retryOnNotExists) { while (true) { + var opened = false; try { - using (new TransactionScope(TransactionScopeOption.Suppress)) - { - _connection.Open(errorsExpected: true); - _connection.Close(); - } + using var _ = new TransactionScope(TransactionScopeOption.Suppress); + _connection.Open(errorsExpected: true); + opened = true; + + _rawSqlCommandBuilder + .Build("SELECT 1") + .ExecuteNonQuery( + new RelationalCommandParameterObject( + _connection, + null, + Dependencies.CurrentContext.Context, + Dependencies.CommandLogger)); return true; } @@ -209,6 +217,13 @@ private bool Exists(bool retryOnNotExists) Thread.Sleep(RetryDelay); } + finally + { + if (opened) + { + _connection.Close(); + } + } } }); @@ -227,14 +242,22 @@ private Task ExistsAsync(bool retryOnNotExists, CancellationToken cancella { while (true) { + var opened = false; + try { - using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) - { - await _connection.OpenAsync(ct, errorsExpected: true); - - await _connection.CloseAsync(); - } + using var _ = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled); + await _connection.OpenAsync(ct, errorsExpected: true); + opened = true; + + await _rawSqlCommandBuilder + .Build("SELECT 1") + .ExecuteNonQueryAsync(new RelationalCommandParameterObject( + _connection, + null, + Dependencies.CurrentContext.Context, + Dependencies.CommandLogger), + ct); return true; } @@ -254,6 +277,13 @@ private Task ExistsAsync(bool retryOnNotExists, CancellationToken cancella await Task.Delay(RetryDelay, ct); } + finally + { + if (opened) + { + await _connection.CloseAsync(); + } + } } }, cancellationToken);