Skip to content

Commit

Permalink
connect only if needed
Browse files Browse the repository at this point in the history
  • Loading branch information
andreasjordan committed Apr 12, 2024
1 parent 160061b commit ffacb22
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
16 changes: 11 additions & 5 deletions public/Connect-DbaInstance.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -594,12 +594,18 @@ function Connect-DbaInstance {
# Test if we have to copy the connection context
# Currently only if we have a different Database or have to switch to a NonPooledConnection or using a specific StatementTimeout or using ApplicationIntent
# We do not test for SqlCredential as this would change the behavior compared to the legacy code path
# Pooled connections are automatically closed, so we need to open the connection to get the ConnectionContext.CurrentDatabase
$null = $inputObject.ConnectionContext.ProcessID
$copyContext = $false
if ($Database -and $inputObject.ConnectionContext.CurrentDatabase -ne $Database) {
Write-Message -Level Verbose -Message "Database provided. Does not match ConnectionContext.CurrentDatabase, copying ConnectionContext and setting the CurrentDatabase"
$copyContext = $true
if ($Database) {
Write-Message -Level Debug -Message "Database [$Database] provided."
if (-not $inputObject.ConnectionContext.CurrentDatabase) {
Write-Message -Level Debug -Message "ConnectionContext.CurrentDatabase is empty, so connection will be opened to get the value"
$inputObject.ConnectionContext.Connect()
Write-Message -Level Debug -Message "ConnectionContext.CurrentDatabase is now [$($inputObject.ConnectionContext.CurrentDatabase)]"
}
if ($inputObject.ConnectionContext.CurrentDatabase -ne $Database) {
Write-Message -Level Verbose -Message "Database [$Database] provided. Does not match ConnectionContext.CurrentDatabase [$($inputObject.ConnectionContext.CurrentDatabase)], copying ConnectionContext and setting the CurrentDatabase"
$copyContext = $true
}
}
if ($ApplicationIntent -and $inputObject.ConnectionContext.ApplicationIntent -ne $ApplicationIntent) {
Write-Message -Level Verbose -Message "ApplicationIntent provided. Does not match ConnectionContext.ApplicationIntent, copying ConnectionContext and setting the ApplicationIntent"
Expand Down
2 changes: 1 addition & 1 deletion public/Invoke-DbaDbDataMasking.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ function Invoke-DbaDbDataMasking {

foreach ($instance in $SqlInstance) {
try {
$server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9 -NonPooledConnection
$server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
} catch {
Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
}
Expand Down

0 comments on commit ffacb22

Please sign in to comment.