ps/Modules/Alkami.PowerShell.SDK/Public/Invoke-SDKSetCompatibilityLevelAllLocalTenants.ps1

78 lines
2.7 KiB
PowerShell
Raw Normal View History

2023-05-30 22:51:22 -07:00
function Invoke-SDKSetCompatibilityLevelAllLocalTenants {
[CmdletBinding()]
param ()
$logLead = Get-LogLeadName
$alkamiMasterConnectionString = (Get-ConnectionString 'AlkamiMaster')
$tenants = Get-FullTenantListFromServer -ConnectionString $alkamiMasterConnectionString
$compatabilityMatrix = @{}
$compatabilitySql = @"
SELECT name, compatibility_level
FROM sys.databases
WHERE compatibility_level < 140
"@
# get the full set of compatability levels for the local environment only
$anyRecord = $false
#region My kingdom for a using statement syntax like C#
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $alkamiMasterConnectionString
$sqlConnection.Open()
[System.Data.SqlClient.SqlCommand]$command = $sqlConnection.CreateCommand()
$command.CommandText = $compatabilitySql
[System.Data.SqlClient.SqlDataReader]$reader = $command.ExecuteReader()
while ($reader.Read()) {
$compatabilityMatrix[$reader[0]] = $reader[1]
$anyRecord = $true
}
$reader.Dispose()
$sqlConnection.Close()
#endregion My kingdom for a using statement syntax like C#
if (!$anyRecord) {
Write-Host "$logLead : All local databases at the minimum expected compatibility_level"
return
}
# We can't just update all of the values to be what we want
# We HAVE to execute on ONLY the local databases that are related to Alkami (which means they are in the tenant table)
$databasesToUpdate = @()
foreach ($tenant in $tenants) {
$sqlconn = New-Object System.Data.SqlClient.SqlConnectionStringBuilder $tenant.ConnectionString
$catalog = $sqlconn.InitialCatalog
if ([string]::IsNullOrWhiteSpace($catalog)) {
$catalog = $tenant.Catalog
}
if ($null -ne $compatabilityMatrix[$catalog]) {
# database is clearly local, and the value is below the threshold
$databasesToUpdate += $catalog
}
}
# Also remember to check the AlkamiMaster connection strings
if ($null -ne $compatabilityMatrix[$sqlConnection.Database]) {
$databasesToUpdate += $sqlConnection.Database
}
if ($databasesToUpdate.Count -eq 0) {
Write-Host "$logLead : No local databases found to update compatibilit_level for"
return
}
$sqlConnection.Open()
foreach ($database in $databasesToUpdate) {
$query = @"
USE master;
ALTER DATABASE [$database] SET COMPATIBILITY_LEVEL = 140;
"@
[System.Data.SqlClient.SqlCommand]$command = $sqlConnection.CreateCommand()
$command.CommandText = $query
$consume = $command.ExecuteNonQuery()
Write-Host "$logLead : Updated compatibility_level for [$database] to 140"
}
$sqlConnection.Close()
$sqlConnection.Dispose()
}