internal/functions/Invoke-DBODeployment.ps1

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
function Invoke-DBODeployment {
    <#
    .SYNOPSIS
        Deploys extracted dbops package from the specified location
 
    .DESCRIPTION
        Deploys an extracted dbops package or plain text scripts with optional parameters.
        Uses a table specified in SchemaVersionTable parameter to determine scripts to run.
        Will deploy all the builds from the package that previously have not been deployed.
 
    .PARAMETER PackageFile
        Path to the dbops package file (usually, dbops.package.json).
 
    .PARAMETER InputObject
        DBOpsPackage object to deploy. Supports pipelining.
 
    .PARAMETER ScriptFile
        A collection of script files to deploy to the server. Accepts Get-Item/Get-ChildItem objects and wildcards.
        Will recursively add all of the subfolders inside folders. See examples if you want only custom files to be added.
        During deployment, scripts will be following this deployment order:
         - Item order provided in the ScriptFile parameter
           - Files inside each child folder (both folders and files in alphabetical order)
             - Files inside the root folder (in alphabetical order)
 
        Aliases: SourcePath
 
    .PARAMETER Configuration
        A custom configuration that will be used during a deployment, overriding existing parameters inside the package.
        Can be a Hashtable, a DBOpsConfig object, or a path to a json file.
 
    .PARAMETER OutputFile
        Log output into specified file.
 
    .PARAMETER Type
        Defines the driver to use when connecting to the database server.
        Available options: SqlServer (default), Oracle
 
    .PARAMETER Append
        Append output to the -OutputFile instead of overwriting it.
 
    .PARAMETER RegisterOnly
        Store deployment script records in the SchemaVersions table without deploying anything.
 
    .PARAMETER Build
        Only deploy certain builds from the package.
 
    .PARAMETER Confirm
        Prompts to confirm certain actions
 
    .PARAMETER WhatIf
        Shows what would happen if the command would execute, but does not actually perform the command
 
    .EXAMPLE
        # Start the deployment of the extracted package from the current folder
        Invoke-DBODeployment
 
    .EXAMPLE
        # Start the deployment of the extracted package from the current folder using specific connection parameters
        Invoke-DBODeployment -SqlInstance 'myserver\instance1' -Database 'MyDb' -ExecutionTimeout 3600
 
    .EXAMPLE
        # Start the deployment of the extracted package using custom logging parameters and schema tracking table
        Invoke-DBODeployment .\Extracted\dbops.package.json -SchemaVersionTable dbo.SchemaHistory -OutputFile .\out.log -Append
 
    .EXAMPLE
        # Start the deployment of the extracted package in the current folder using variables instead of specifying values directly
        Invoke-DBODeployment -SqlInstance '#{server}' -Database '#{db}' -Configuration @{ Variables = @{server = 'myserver\instance1'; db = 'MyDb'} }
#>


    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'PackageFile')]
    Param (
        [parameter(ParameterSetName = 'PackageFile')]
        [string]$PackageFile = ".\dbops.package.json",
        [parameter(ParameterSetName = 'Script')]
        [Alias('SourcePath')]
        [object[]]$ScriptFile,
        [parameter(ParameterSetName = 'PackageObject')]
        [Alias('Package')]
        [object]$InputObject,
        [parameter(ParameterSetName = 'PackageObject')]
        [parameter(ParameterSetName = 'PackageFile')]
        [string[]]$Build,
        [string]$OutputFile,
        [switch]$Append,
        [Alias('ConnectionType', 'ServerType')]
        [DBOps.ConnectionType]$Type = (Get-DBODefaultSetting -Name rdbms.type -Value),
        [object]$Configuration,
        [switch]$RegisterOnly
    )
    begin {
        Function Get-DeploymentScript {
            Param (
                $Script,
                $Variables
            )
            $scriptDeploymentPath = $Script.GetDeploymentPath()
            Write-PSFMessage -Level Debug -Message "Adding script $scriptDeploymentPath"
            # Replace tokens in the scripts
            $scriptContent = Resolve-VariableToken -InputObject $Script.GetContent() -Runtime $Variables
            return [DbUp.Engine.SqlScript]::new($scriptDeploymentPath, $scriptContent)
        }
        Function Initialize-DbUpBuilder {
            Param (
                $Script,
                $Connection,
                $Log,
                $Config,
                $Type,
                $Status,
                $Journal
            )
            # Create DbUpBuilder based on the connection
            $dbUp = Get-DbUpBuilder -Connection $Connection -Type $Type -Script $Script -Config $Config
            # Assign logging
            $dbUp = [StandardExtensions]::LogTo($dbUp, $Log)
            $dbUp = [StandardExtensions]::LogScriptOutput($dbUp)
            # Assign a journal
            if (-Not $Journal) {
                $Journal = Get-DbUpJournal -Connection { $Connection } -Log { $Log } -SchemaVersionTable $null -Type $Type
            }
            $dbUp = [StandardExtensions]::JournalTo($dbUp, $Journal)
            return $dbUp
        }
        Function Invoke-DbUpDeployment {
            Param (
                $DbUp,
                $Status
            )
            $dbUpBuild = $DbUp.Build()
            $upgradeResult = $dbUpBuild.PerformUpgrade()
            $Status.Successful = $upgradeResult.Successful
            $Status.Error = $upgradeResult.Error
            $Status.Scripts += $upgradeResult.Scripts
            if (!$Status.Successful) {
                # Throw output error if unsuccessful
                if ($Status.Error) {
                    throw $Status.Error
                }
                else {
                    Stop-PSFFunction -EnableException $true -Message 'Deployment failed. Failed to retrieve error record'
                }
            }
        }
    }
    process {
        $config = New-DBOConfig
        if ($PsCmdlet.ParameterSetName -eq 'PackageFile') {
            # Get package object from the json file
            $package = Get-DBOPackage $PackageFile -Unpacked
        }
        elseif ($PsCmdlet.ParameterSetName -eq 'PackageObject') {
            $package = Get-DBOPackage -InputObject $InputObject
        }
        # Merge package config into the current config
        if ($package) {
            $config = $config | Get-DBOConfig -Configuration $package.Configuration
        }
        # Merge custom config into the current config
        if (Test-PSFParameterBinding -ParameterName Configuration) {
            $config = $config | Get-DBOConfig -Configuration $Configuration
        }

        # Initialize external libraries if needed
        Write-PSFMessage -Level Debug -Message "Initializing libraries for $Type"
        Initialize-ExternalLibrary -Type $Type

        # Replace tokens if any
        Write-PSFMessage -Level Debug -Message "Replacing variable tokens"
        foreach ($property in [DBOpsConfig]::EnumProperties() | Where-Object { $_ -ne 'Variables' }) {
            $config.SetValue($property, (Resolve-VariableToken $config.$property $config.Variables))
        }

        $scriptCollection = @()
        $preScriptCollection = @()
        $postScriptCollection = @()
        if ($PsCmdlet.ParameterSetName -ne 'Script') {
            # Get contents of the script files
            if ($Build) {
                $buildCollection = $package.GetBuild($Build)
            }
            else {
                $buildCollection = $package.GetBuilds()
            }
            if (!$buildCollection) {
                Stop-PSFFunction -Message "No builds selected for deployment, no deployment will be performed." -EnableException $false
                return
            }
            foreach ($buildItem in $buildCollection) {
                foreach ($script in $buildItem.scripts) {
                    $scriptCollection += Get-DeploymentScript -Script $script -Variables $config.Variables
                }
            }
            foreach ($preScript in $package.GetPreScripts()) {
                $preScriptCollection += Get-DeploymentScript -Script $preScript -Variables $config.Variables
            }
            foreach ($postScript in $package.GetPostScripts()) {
                $postScriptCollection += Get-DeploymentScript -Script $postScript -Variables $config.Variables
            }
        }
        else {
            foreach ($scriptItem in $ScriptFile) {
                if ($scriptItem -and $scriptItem -isnot [DBOpsFile]) {
                    Stop-PSFFunction -Message "Expected DBOpsFile object, got [$($scriptItem.GetType().FullName)]." -EnableException $true
                    return
                }
                Write-PSFMessage -Level Debug -Message "Adding deployment script $($scriptItem.FullName) as $($scriptItem.PackagePath)"
                if (!$RegisterOnly) {
                    # Replace tokens in the scripts
                    $scriptContent = Resolve-VariableToken $scriptItem.GetContent() $config.Variables
                }
                else {
                    $scriptContent = ""
                }
                $scriptCollection += [DbUp.Engine.SqlScript]::new($scriptItem.PackagePath, $scriptContent)
            }
        }

        Write-PSFMessage -Level Debug -Message "Creating DbUp objects"
        # Create DbUp connection object
        $csBuilder = Get-ConnectionString -Configuration $config -Type $Type -Raw
        $connString = $csBuilder.ToString()
        $dbUpConnection = Get-ConnectionManager -ConnectionString $connString -Type $Type

        # Create an output object
        $status = [DBOpsDeploymentStatus]::new()
        $status.StartTime = [datetime]::Now
        $status.Configuration = $config
        if (!$ConnectionString) {
            $status.SqlInstance = $config.SqlInstance
            $status.Database = $config.Database
        }
        $status.ConnectionType = $Type
        if ($PsCmdlet.ParameterSetName -eq 'Script') {
            foreach ($p in $ScriptFile) {
                $status.SourcePath += Join-PSFPath -Normalize $p.FullName
            }
        }
        else {
            $status.SourcePath = $package.FileName
        }

        # Create a logging object using dbopsConsoleLog class implementing a logging Interface
        $dbUpLog = [DBOpsLog]::new($config.Silent, $OutputFile, $Append, $status)
        $dbUpLog.CallStack = (Get-PSCallStack)[1]

        # Define schema versioning (journalling)
        $dbUpTableJournal = Get-DbUpJournal -Connection { $dbUpConnection } -Log { $dbUpLog } -Schema $config.Schema -SchemaVersionTable $config.SchemaVersionTable -Type $Type

        # Initialize DbUp object with deployment parameters
        $dbUp = Initialize-DbUpBuilder -Script $scriptCollection -Config $config -Type $Type -Connection $dbUpConnection -Log $dbUpLog -Status $status -Journal $dbUpTableJournal

        # Create database if necessary for supported platforms
        if ($config.CreateDatabase) {
            if ($PSCmdlet.ShouldProcess("Ensuring the target database exists")) {
                Write-PSFMessage -Level Debug -Message "Creating database if not exists"
                $null = Invoke-EnsureDatabase -ConnectionString $connString -Log $dbUpLog -Timeout $config.ExecutionTimeout -Type $Type
            }
        }
        # Register only
        if ($RegisterOnly) {
            # Cycle through already registered files and register the ones that are missing
            if ($PSCmdlet.ShouldProcess($package, "Registering the package")) {
                $registeredScripts = @()
                $managedConnection = $dbUpConnection.OperationStarting($dbUpLog, $null)
                $deployedScripts = $dbUpTableJournal.GetExecutedScripts()
                try {
                    foreach ($script in $scriptCollection) {
                        if ($script.Name -notin $deployedScripts) {
                            Write-PSFMessage -Level Debug -Message "Registering script $($script.Name)"
                            $dbUpConnection.ExecuteCommandsWithManagedConnection( {
                                    Param (
                                        $dbCommandFactory
                                    )
                                    $dbUpTableJournal.StoreExecutedScript($script, $dbCommandFactory)
                                })
                            $registeredScripts += $script
                            $dbUpLog.WriteInformation("{0} was registered in table {1}", @($script.Name, $config.SchemaVersionTable))
                        }
                    }
                    $status.Successful = $true
                }
                catch {
                    $status.Successful = $false
                    Stop-PSFFunction -EnableException $true -Message "Failed to register the script $($script.Name)" -ErrorRecord $_
                }
                finally {
                    $managedConnection.Dispose()
                    $status.Scripts = $registeredScripts
                }
            }
            else {
                $status.Successful = $true
                $status.DeploymentLog += "Running in WhatIf mode - no registration performed."
            }
            $status.EndTime = [datetime]::Now
            $status
            if (!$status.Successful) {
                # Throw output error if unsuccessful
                if ($status.Error) {
                    throw $status.Error
                }
                else {
                    Stop-PSFFunction -EnableException $true -Message 'Script registration failed. Failed to retrieve error record'
                }
            }
        }
        else {
            try {
                # Pre scripts
                if ($preScriptCollection) {
                    # create a new non-journalled connection
                    $dbUpPre = Initialize-DbUpBuilder -Script $preScriptCollection -Config $config -Type $Type -Connection $dbUpConnection -Log $dbUpLog -Status $status
                    if ($PSCmdlet.ShouldProcess($package, "Deploying pre-scripts")) {
                        Write-PSFMessage -Level Debug -Message "Deploying pre-scripts"
                        Invoke-DbUpDeployment -DbUp $dbUpPre -Status $status
                    }
                    else {
                        foreach ($script in $preScriptCollection) {
                            $status.Scripts += $script
                            $dbUpLog.WriteInformation("{0} would have been executed - WhatIf mode.", $script.Name)
                        }
                        $status.Successful = $true
                        $dbUpLog.WriteInformation("No pre-deployment performed - WhatIf mode.", $null)
                    }
                }
                # Build and Upgrade
                if ($PSCmdlet.ShouldProcess($package, "Deploying the package")) {
                    Write-PSFMessage -Level Debug -Message "Performing deployment"
                    Invoke-DbUpDeployment -DbUp $dbUp -Status $status
                }
                else {
                    $missingScripts = @()
                    $managedConnection = $dbUpConnection.OperationStarting($dbUpLog, $null)
                    $deployedScripts = $dbUpTableJournal.GetExecutedScripts()
                    foreach ($script in $scriptCollection) {
                        if ($script.Name -notin $deployedScripts) {
                            $missingScripts += $script
                            $dbUpLog.WriteInformation("{0} would have been executed - WhatIf mode.", $script.Name)
                        }
                    }
                    $managedConnection.Dispose()
                    $status.Scripts += $missingScripts
                    $status.Successful = $true
                    $dbUpLog.WriteInformation("No deployment performed - WhatIf mode.", $null)
                }
                # Post scripts
                if ($postScriptCollection) {
                    # create a new non-journalled connection
                    $dbUpPost = Initialize-DbUpBuilder -Script $postScriptCollection -Config $config -Type $Type -Connection $dbUpConnection -Log $dbUpLog -Status $status
                    if ($PSCmdlet.ShouldProcess($package, "Deploying post-scripts")) {
                        Write-PSFMessage -Level Debug -Message "Deploying post-scripts"
                        Invoke-DbUpDeployment -DbUp $dbUpPost -Status $status
                    }
                    else {
                        foreach ($script in $postScriptCollection) {
                            $status.Scripts += $script
                            $dbUpLog.WriteInformation("{0} would have been executed - WhatIf mode.", $script.Name)
                        }
                        $status.Successful = $true
                        $dbUpLog.WriteInformation("No post-deployment performed - WhatIf mode.", $null)
                    }
                }
            }
            catch {
                throw $_
            }
            finally {
                $status.EndTime = [datetime]::Now
                $status
            }
        }
    }
    end { }
}