Instantly share code, notes, and snippets.

Embed
What would you like to do?
DB Deployments with Rollbacks using EF Core and OD
param(
$Folder = $OctopusParameters['Folder'],
$IncludePattern = $OctopusParameters['IncludePattern'],
$RetainCount = $OctopusParameters['RetainCount']
)
Write-Host "Applying retention policy..."
Get-ChildItem "$Folder" -Filter "$IncludePattern" `
| Sort-Object LastWriteTime -Descending `
| Select-Object -Skip $RetainCount `
| % {
Write-Host "Deleting $_"
Remove-Item "$Folder\$_"
}
Write-Host "Done"
param(
$Database = $OctopusParameters['Database'],
$Server = $OctopusParameters['DatabaseServer'],
$BackupLocation = $OctopusParameters['DbBackupLocation']
)
function Invoke-SqlCommand {
param(
[Parameter(ParameterSetName='file')]
[string]$InputFile,
[Parameter(ParameterSetName='inline')]
[string]$Query
)
Push-Location
if ($Query -ne $null) {
Invoke-SqlCmd -ServerInstance $Server -Database $Database -OutputSqlErrors $true -Verbose -ErrorAction Stop -Query $Query
} elseif ($InputFile -ne $null) {
Invoke-SqlCmd -ServerInstance $Server -Database $Database -OutputSqlErrors $true -Verbose -ErrorAction Stop -InputFile $InputFile
} else {
throw "Neither -Query nor -InputFile specified for Invoke-SqlCommand"
}
Pop-Location
}
function Get-AppliedMigrations {
$migrationsTableExists = (
Invoke-SqlCommand `
-Query @"SELECT CASE WHEN EXISTS (SELECT * FROM [sys].[tables] WHERE [name] = '__EFMigrationsHistory') THEN 1 ELSE 0 END AS MigrationsTableExists").MigrationsTableExists -eq 1
if ($migrationsTableExists) {
$appliedMigrations = Invoke-SqlCommand -Query 'SELECT MigrationId FROM [__EFMigrationsHistory]' | Select-Object -ExpandProperty MigrationId
}
else {
$appliedMigrations = @()
}
return $appliedMigrations
}
function Find-PendingMigrations {
$appliedMigrations = Get-AppliedMigrations
$allMigrations = Get-ChildItem "scripts" -Name | ForEach-Object { $_.Replace(".sql", "") }
$allMigrations | Where-Object { $_ -NotIn $appliedMigrations }
}
$pendingMigrations = Find-PendingMigrations
if ($pendingMigrations.Length -eq 0) {
Write-Host "No pending migrations - we're done!"
return
}
$BackupFile = "$BackupLocation\ActDb_backup_$(Get-Date -Format "yyyy-MM-dd_HH-mm-ss").bak"
Write-Host "Backing up $Server\$Database to $BackupFile..."
Backup-SqlDatabase `
-ServerInstance $Server `
-Database $Database `
-BackupFile $BackupFile `
-BackupAction Database `
-CopyOnly `
-ErrorAction Stop `
-Verbose
Write-Host "Backup done!"
try {
foreach ($migration in $pendingMigrations) {
Write-Host "Applying $migration..."
SQLCMD.EXE -S $Server -d $Database -i ./TransactionWrapper.sql -v ScriptFile = "scripts/$migration.sql" -b
if ($LASTEXITCODE -ne 0) {
throw "$migration failed!"
}
}
Write-Host "All migrations applied!"
} catch {
Write-Warning "DB Migration failed; restoring from backup..."
Invoke-SqlCommand -Query "ALTER DATABASE [$Database] SET OFFLINE WITH ROLLBACK IMMEDIATE"
Restore-SqlDatabase `
-ServerInstance $Server `
-Database $Database `
-BackupFile $BackupFile `
-ReplaceDatabase `
-ErrorAction Stop `
-Verbose
Invoke-SqlCommand -Query "ALTER DATABASE [$Database] SET ONLINE"
Write-Host "Backup restored!"
throw $_.Exception
}

Copyright 2017 Jayway Stockholm AB

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?xml version="1.0" encoding="utf-8" ?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<!-- ... -->
</metadata>
<files>
<file src="scripts\*.sql" target="scripts" />
<file src="Deploy.ps1" target="" />
<file src="TransactionWrapper.sql" target="" />
</files>
</package>
param(
$Version = '0.0.0'
)
# Restore and build the project, to ensure that we have the latest bits and the EF Core tooling available
dotnet restore
dotnet build
# List all the migrations in the project
$migrations = dotnet ef migrations list --no-build
$previous = '0'
# For each migration, create a plain SQL script that applies the migration to a database
foreach ($migration in $migrations)
{
dotnet ef migrations script $previous $migration --idempotent --no-build --output "./scripts/$migration.sql"
$previous = $migration
}
# Package all the scripts into a NuGet package, which can be pushed to Octopus Deploy
nuget pack MyApp.Db.nuspec -Version $Version -NoPackageAnalysis
$ProjectId = $OctopusParameters['Octopus.Project.ID']
$EnvironmentId = $OctopusParameters['Octopus.Environment.ID']
function Get-LastSuccessfulReleaseId {
param(
[string]$ProjectId,
[string]$EnvironmentId
)
$progression = Invoke-RestMethod `
-Method Get `
-Uri "$OctopusURL/api/progression/$ProjectId" `
-Headers @{ "X-Octopus-ApiKey" = $octopusAPIKey }
$lastSuccessfulRelease = $progression.Releases `
| ? { $_.Deployments.$EnvironmentID -ne $null } `
| select -ExpandProperty Deployments `
| select -ExpandProperty $EnvironmentID `
| ? { $_.State -eq 'Success' } `
| sort -Descending CompletedTime `
| select -First 1 `
| select -ExpandProperty ReleaseId
return $lastSuccessfulRelease
}
function Invoke-DeployRelease {
param(
[string]$ReleaseId,
[string]$EnvironmentId
)
Invoke-RestMethod `
-Method Post `
-Uri "$OctopusURL/api/deployments" `
-Body (@{ ReleaseId = $ReleaseId; EnvironmentId = $EnvironmentId } | ConvertTo-Json) `
-ContentType 'application/json' `
-Headers @{ "X-Octopus-ApiKey" = $octopusAPIKey }
}
$lastSuccessfulRelease = Get-LastSuccessfulReleaseId -ProjectId "Projects-1" -EnvironmentId "Environments-1"
Invoke-DeployRelease -ReleaseId $lastSuccessfulRelease -EnvironmentId $EnvironmentID
:On Error Exit
SET XACT_ABORT ON
BEGIN TRANSACTION
:r $(ScriptFile)
COMMIT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment