Skip to content

Commit b94e33e

Browse files
Connect-DbaInstance: Auto-retry with Initial Catalog=master for mirrored SQL Server instances (#10215)
1 parent 480e72a commit b94e33e

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

public/Connect-DbaInstance.ps1

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1130,6 +1130,37 @@ function Connect-DbaInstance {
11301130
}
11311131
}
11321132

1133+
# Check if the error is about Failover Partner requiring Initial Catalog.
1134+
# This happens when connecting to a SQL Server instance configured for database mirroring.
1135+
# The .NET SqlClient sends Failover Partner info from the server's TDS handshake to the
1136+
# connection pool, and the pool then requires Initial Catalog to be set in the connection string.
1137+
$isFailoverPartnerError = $errorMessage -match "Failover Partner" -and $errorMessage -match "Initial Catalog"
1138+
if ($isNewConnection -and $isFailoverPartnerError -and -not $connectionSucceeded -and $inputObjectType -eq 'String') {
1139+
Write-Message -Level Verbose -Message "Connection failed because the server is configured for database mirroring (Failover Partner requires Initial Catalog). Retrying with Initial Catalog=master."
1140+
Write-Message -Level Debug -Message "Original error: $errorMessage"
1141+
1142+
try {
1143+
# Add Initial Catalog=master to satisfy the Failover Partner connection string requirement
1144+
if ($server.ConnectionContext.SqlConnectionObject.ConnectionString -notmatch "Initial Catalog" -and $server.ConnectionContext.SqlConnectionObject.ConnectionString -notmatch "Database=") {
1145+
if ($server.ConnectionContext.SqlConnectionObject.ConnectionString -match ";$") {
1146+
$server.ConnectionContext.SqlConnectionObject.ConnectionString += "Initial Catalog=master;"
1147+
} else {
1148+
$server.ConnectionContext.SqlConnectionObject.ConnectionString += ";Initial Catalog=master;"
1149+
}
1150+
}
1151+
1152+
# Retry the connection
1153+
Write-Message -Level Debug -Message "Retrying connection with Initial Catalog=master for server with database mirroring"
1154+
$null = $server.ConnectionContext.ExecuteWithResults("SELECT 'dbatools is opening a new connection with Initial Catalog'")
1155+
Write-Message -Level Verbose -Message "Connection succeeded with Initial Catalog=master for server with database mirroring"
1156+
$connectionSucceeded = $true
1157+
} catch {
1158+
Write-Message -Level Debug -Message "Retry with Initial Catalog=master also failed: $($_.Exception.Message)"
1159+
# Keep the original error for reporting
1160+
$connectionError = $_
1161+
}
1162+
}
1163+
11331164
if (-not $connectionSucceeded) {
11341165
Stop-Function -Target $instance -Message "Failure" -Category ConnectionError -ErrorRecord $connectionError -Continue
11351166
}

0 commit comments

Comments
 (0)