-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions-ps7.0.ps1
More file actions
384 lines (324 loc) · 9.06 KB
/
functions-ps7.0.ps1
File metadata and controls
384 lines (324 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
using namespace Microsoft.Data.SqlClient
function Get-FileChecksum {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$File
)
(Get-FileHash -Path $File -Algorithm SHA256).Hash
}
function Get-RelativePath {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$RelativeTo,
[Parameter(Mandatory)]
[string]$Path
)
[System.IO.Path]::GetRelativePath($RelativeTo, $Path)
}
function Get-Executed {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$ConnStr,
[Parameter(Mandatory)]
[string]$Phase
)
$sqlConn = $null
$sqlCmd = $null
$sqlReader = $null
try {
$sqlConn = [SQLConnection]::new()
$sqlConn.ConnectionString = $ConnStr
$query = @'
select script_name, [checksum]
from dbo.easy_migration_history
where phase = @phase
'@
$sqlConn.Open()
$sqlCmd = [SqlCommand]::new($query, $sqlConn)
$sqlCmd.CommandType = [System.Data.CommandType]::Text
$pPhase = $sqlCmd.Parameters.Add('@phase', [System.Data.SqlDbType]::NVarChar, 32)
$pPhase.Value = $Phase
$sqlReader = $sqlCmd.ExecuteReader()
while ($sqlReader.Read()) {
[PSCustomObject]@{
script_name = $sqlReader['script_name'].ToLower()
checksum = $sqlReader['checksum']
}
}
}
finally {
if ($null -ne $sqlReader) {
$sqlReader.Close()
$sqlReader.Dispose()
}
if ($null -ne $sqlCmd) {
$sqlCmd.Dispose()
}
if ($null -ne $sqlConn) {
$sqlConn.Close()
$sqlConn.Dispose()
}
}
}
function Set-Executed {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$ConnStr,
[Parameter(Mandatory)]
[string]$ScriptName,
[Parameter(Mandatory)]
[string]$Phase,
[Parameter(Mandatory)]
[string]$Checksum,
[Parameter(Mandatory)]
[bool]$ForceScript
)
$sqlConn = $null
$sqlCmd = $null
try {
$sqlConn = [SQLConnection]::new()
$sqlConn.ConnectionString = $ConnStr
$query = ''
if ($ForceScript) {
$query = @'
update dbo.easy_migration_history
set [checksum] = @checksum, executed_at = sysutcdatetime()
where script_name = @script_name and phase = @phase
if @@rowcount = 0
begin
raiserror('Forced execution failed. The script was not found in the migration history table',16,1)
end
'@
}
else {
$query = @'
insert dbo.easy_migration_history(script_name, phase, [checksum])
values(@script_name, @phase, @checksum)
'@
}
$sqlConn.Open()
$sqlCmd = [SqlCommand]::new($query, $sqlConn)
$sqlCmd.CommandType = [System.Data.CommandType]::Text
$pScriptName = $sqlCmd.Parameters.Add('@script_name', [System.Data.SqlDbType]::NVarChar)
$pScriptName.Value = $ScriptName
$pPhase = $sqlCmd.Parameters.Add('@phase', [System.Data.SqlDbType]::NVarChar, 32)
$pPhase.Value = $Phase
$pChecksum = $sqlCmd.Parameters.Add('@checksum', [System.Data.SqlDbType]::Char, 64)
$pChecksum.Value = $Checksum
$sqlCmd.ExecuteNonQuery() | Out-Null # Out-Null to suppress the output
}
finally {
if ($null -ne $sqlCmd) {
$sqlCmd.Dispose()
}
if ($null -ne $sqlConn) {
$sqlConn.Close()
$sqlConn.Dispose()
}
}
}
function Invoke-Migration {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$ConnStr,
[Parameter(Mandatory)]
[string]$Script
)
try {
Invoke-Sqlcmd -ConnectionString $ConnStr -InputFile $Script -AbortOnError | Out-Null
}
catch {
Write-Error "Failed to run migration script: $Script"
throw
}
}
function Get-Migrations {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$ConfigFile,
[Parameter(Mandatory)]
[string]$Phase
)
$json = Get-Content $ConfigFile -Raw | ConvertFrom-Json
$first = $json.PSObject.Properties.Match($Phase)
if (-not $first -or $first.Count -eq 0) {
throw "Migration phase not found: $Phase"
}
$first[0].Value.scripts | ForEach-Object { $_.ToLower() }
}
function Invoke-EasyMigration {
<#
.SYNOPSIS
Deploys migration scripts to the target SQL Server
https://github.com/corelevel/easy-migration
.DESCRIPTION
Deploys migration scripts to the target SQL Server in order
Detects checksum drift and stops on mismatch
Requires PowerShell 7.0+
Requires SQL Server PowerShell module
https://learn.microsoft.com/en-us/powershell/sql-server/download-sql-server-ps-module
.PARAMETER ConnStr
SQL Server connection string
.PARAMETER BasePath
Folder containing config file and migration scripts
.PARAMETER Phase
Migration phase to execute
.PARAMETER IgnoreScripts
Optional list of scripts to skip during execution
Filenames must match entries defined in the configuration file
Example: "001-fix-that.sql", "000-fix-this.sql"
.PARAMETER ForceScripts
Optional list of migration script filenames to force execution even if
they were previously recorded in the migration history table
Filenames must match entries defined in the configuration file
Example: "job007\000-kill-all-user-processes.sql"
.INPUTS
{
"phase01": {
"scripts": [
"001-fix-that.sql",
"000-fix-this.sql",
"job007\\000-kill-all-user-processes.sql"
]
},
"phase02": {
"scripts": [
"000-do-cool-stuff.sql"
]
},
"phase03": {
"scripts": [
"000-fix-this.sql"
]
}
}
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(Mandatory)]
[string]$ConnStr,
[Parameter(Mandatory)]
[ValidateScript({ Test-Path $_ -PathType Container })]
[string]$BasePath,
[Parameter(Mandatory)]
[string]$Phase,
[string[]]$IgnoreScripts,
[string[]]$ForceScripts
)
Set-StrictMode -Version Latest
try {
$configFile = Join-Path $BasePath 'migration.json'
$scriptsFolder = Join-Path $BasePath $Phase
if (-not (Test-Path $configFile -PathType Leaf)) {
throw "Migration configuration not found: $configFile"
}
if (-not (Test-Path $scriptsFolder -PathType Container)) {
throw "Scripts folder not found: $scriptsFolder"
}
$executedScriptList = @(Get-Executed -ConnStr $ConnStr -Phase $Phase)
$scriptList = @(Get-Migrations -ConfigFile $configFile -Phase $Phase)
# Converting provided migration script lists to lower case
if ($IgnoreScripts) {
$IgnoreScripts = $IgnoreScripts | ForEach-Object { $_.ToLower() }
}
if ($ForceScripts) {
$ForceScripts = $ForceScripts | ForEach-Object { $_.ToLower() }
}
# Check for duplicates
$duplicates = $scriptList | Group-Object | Where-Object Count -gt 1
if ($duplicates) {
$names = ($duplicates | Select-Object -ExpandProperty Name) -join ', '
throw "Duplicate script names detected in configuration: $names"
}
# Check for intersection
if ($IgnoreScripts -and $ForceScripts) {
$names = $IgnoreScripts | Where-Object { $_ -in $ForceScripts }
if ($names) {
throw "Scripts cannot be both ignored and forced: $($names -join ', ')"
}
}
$dryRun = $true
$connStrParser = [SqlConnectionStringBuilder]::new($ConnStr)
$target = "DataSource: $($connStrParser.DataSource), InitialCatalog: " +
"$($connStrParser.InitialCatalog), Phase: $Phase"
if ($PSCmdlet.ShouldProcess($target)) {
$dryRun = $false
}
else {
Write-Verbose 'Dry run'
}
$executedScriptMap = @{}
foreach ($script in $executedScriptList) {
$executedScriptMap[$script.script_name] = $script.checksum
}
if ($IgnoreScripts) {
$notPresent = $IgnoreScripts | Where-Object { $_ -notin $scriptList }
if ($notPresent) {
Write-Warning "IgnoreScripts contains names not present in configuration: " +
"$($notPresent -join ', ')"
}
}
if ($ForceScripts) {
$notPresent = $ForceScripts | Where-Object { $_ -notin $scriptList }
if ($notPresent) {
Write-Warning "ForceScripts contains names not present in configuration: " +
"$($notPresent -join ', ')"
}
}
$didGoodJob = $false
foreach ($scriptName in $scriptList) {
if ($IgnoreScripts) {
if ($IgnoreScripts.Contains($scriptName)) {
Write-Verbose "Ignoring migration script: $scriptName"
continue
}
}
$forceScript = $false
if ($ForceScripts) {
if ($ForceScripts.Contains($scriptName)) {
Write-Verbose "Forcing migration script: $scriptName"
$forceScript = $true
}
}
$scriptFullPath = Join-Path $scriptsFolder $scriptName
if (-not (Test-Path $scriptFullPath -PathType Leaf)) {
throw "Migration script not found: $scriptFullPath"
}
$scriptExecuted = $executedScriptMap.ContainsKey($scriptName)
# Check for checksum difference
$checksum = Get-FileChecksum -File $scriptFullPath
if (-not $forceScript -and $scriptExecuted) {
$executedChecksum = $executedScriptMap[$scriptName]
if ($checksum -ne $executedChecksum) {
throw "Checksum mismatch for migration script: $scriptName"
}
continue
}
$didGoodJob = $true
Write-Verbose "Running migration script: $scriptName"
if (-not $dryRun) {
Invoke-Migration -ConnStr $ConnStr -Script $scriptFullPath
$scriptName = Get-RelativePath -RelativeTo $scriptsFolder -Path $scriptFullPath
Set-Executed -ConnStr $ConnStr -ScriptName $scriptName -Phase $Phase.ToLower() `
-Checksum $checksum -ForceScript ($forceScript -and $scriptExecuted)
}
Write-Verbose 'Migration completed'
}
if (-not $didGoodJob) {
Write-Verbose 'Nothing to run'
}
else {
Write-Verbose 'Easy as that!'
}
}
catch {
Write-Error "Failed to run migration: $_"
throw
}
}