Skip to content

Commit

Permalink
Fix stale cache issue in Add-DbaAgDatabase (#9094)
Browse files Browse the repository at this point in the history
Signed-off-by: Klaus Frank <[email protected]>
Co-authored-by: Chrissy LeMaire <[email protected]>
  • Loading branch information
agowa and potatoqualitee authored Sep 28, 2023
1 parent f7c8a4e commit 447ae1e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
8 changes: 8 additions & 0 deletions public/Add-DbaAgDatabase.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,14 @@ function Add-DbaAgDatabase {

try {
$replicaAgDb = Get-DbaAgDatabase -SqlInstance $replicaServerSMO[$replicaName] -AvailabilityGroup $AvailabilityGroup -Database $db.Name -EnableException
if ($null -eq $replicaAgDb) {
# We know the database has to exist by now, so we refresh the AvailabilityGroup object to update the cache that claims it doesn't.
$replicaAgDb = Get-DbaAgDatabase -Refresh -SqlInstance $replicaServerSMO[$replicaName] -AvailabilityGroup $AvailabilityGroup -Database $db.Name -EnableException
if ($null -eq $replicaAgDb) {
# throws to a catch
throw [System.Management.Automation.ItemNotFoundException]::New()
}
}
} catch {
$failure = $true
Stop-Function -Message "Failed to get database $($db.Name) on replica $replicaName." -ErrorRecord $_ -Continue
Expand Down
8 changes: 8 additions & 0 deletions public/Get-DbaAgDatabase.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ function Get-DbaAgDatabase {
$InputObject += Get-DbaAvailabilityGroup -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup
}

foreach ($ag in $InputObject) {
$null = $ag.Refresh()
# Calling AvilabilityReplica.Refresh() has the side effct of updating AvailabilityDatabases.
# calling AvailabilityDatabases.Refresh() alone is not enough
$null = $ag.AvailabilityReplicas.Refresh()
$null = $ag.AvailabilityDatabases.Refresh()
}

foreach ($db in $InputObject.AvailabilityDatabases) {
if ($Database) {
if ($db.Name -notin $Database) { continue }
Expand Down

0 comments on commit 447ae1e

Please sign in to comment.