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
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 ScriptPath
        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 ScriptPath parameter
           - Files inside each child folder (both folders and files in alphabetical order)
             - Files inside the root folder (in alphabetical order)
              
        Aliases: SourcePath
     
    .PARAMETER SqlInstance
        Database server to connect to. SQL Server only for now.
        Aliases: Server, SQLServer, DBServer, Instance
     
    .PARAMETER Database
        Name of the database to execute the scripts in. Optional - will use default database if not specified.
     
    .PARAMETER DeploymentMethod
        Choose one of the following deployment methods:
        - SingleTransaction: wrap all the deployment scripts into a single transaction and rollback whole deployment on error
        - TransactionPerScript: wrap each script into a separate transaction; rollback single script deployment in case of error
        - NoTransaction: deploy as is
         
        Default: NoTransaction
     
    .PARAMETER ConnectionTimeout
        Database server connection timeout in seconds. Only affects connection attempts. Does not affect execution timeout.
        If 0, will wait for connection until the end of times.
         
        Default: 30
         
    .PARAMETER ExecutionTimeout
        Script execution timeout. The script will be aborted if the execution takes more than specified number of seconds.
        If 0, the script is allowed to run until the end of times.
 
        Default: 0
     
    .PARAMETER Encrypt
        Enables connection encryption.
     
    .PARAMETER Credential
        PSCredential object with username and password to login to the database server.
     
    .PARAMETER UserName
        An alternative to -Credential - specify username explicitly
     
    .PARAMETER Password
        An alternative to -Credential - specify password explicitly
     
    .PARAMETER SchemaVersionTable
        A table that will hold the history of script execution. This table is used to choose what scripts are going to be
        run during the deployment, preventing the scripts from being execured twice.
        If set to $null, the deployment will not be tracked in the database. That will also mean that all the scripts
        and all the builds from the package are going to be deployed regardless of any previous deployment history.
 
        Default: SchemaVersions
     
    .PARAMETER Silent
        Will supress all output from the command.
     
    .PARAMETER Variables
        Hashtable with variables that can be used inside the scripts and deployment parameters.
        Proper format of the variable tokens is #{MyVariableName}
        Can also be provided as a part of Configuration hashtable: -Configuration @{ Variables = @{ Var1 = ...; Var2 = ...}}
        Will augment and/or overwrite Variables defined inside the package.
 
    .PARAMETER OutputFile
        Log output into specified file.
         
    .PARAMETER ConnectionType
        Defines the driver to use when connecting to the database server.
        Available options: SqlServer (default), Oracle
         
    .PARAMETER ConnectionString
        Use a custom connection string to connect to the database server.
     
    .PARAMETER Schema
        Deploy into a specific schema (if supported by RDBMS)
         
    .PARAMETER Append
        Append output to the -OutputFile instead of overwriting it.
 
    .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}' -Variables @{server = 'myserver\instance1'; db = 'MyDb'}
#>

    
    [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = 'PackageFile')]
    Param (
        [parameter(ParameterSetName = 'PackageFile')]
        [string]$PackageFile = ".\dbops.package.json",
        [parameter(ParameterSetName = 'Script')]
        [Alias('SourcePath')]
        [string[]]$ScriptPath,
        [parameter(ParameterSetName = 'Pipeline')]
        [Alias('Package')]
        [object]$InputObject,
        [Alias('Server', 'SqlServer', 'DBServer', 'Instance')]
        [string]$SqlInstance,
        [string]$Database,
        [ValidateSet('SingleTransaction', 'TransactionPerScript', 'NoTransaction')]
        [string]$DeploymentMethod = 'NoTransaction',
        [int]$ConnectionTimeout,
        [int]$ExecutionTimeout,
        [switch]$Encrypt,
        [pscredential]$Credential,
        [string]$UserName,
        [securestring]$Password,
        [AllowNull()]
        [string]$SchemaVersionTable,
        [switch]$Silent,
        [string]$OutputFile,
        [switch]$Append,
        [hashtable]$Variables,
        [ValidateSet('SQLServer', 'Oracle')]
        [Alias('Type', 'ServerType')]
        [string]$ConnectionType = 'SQLServer',
        [string]$ConnectionString,
        [string]$Schema
    )
    begin {}
    process {
        if ($PsCmdlet.ParameterSetName -eq 'PackageFile') {
            #Get package object from the json file
            $package = Get-DBOPackage $PackageFile -Unpacked
            $config = $package.Configuration
        }
        elseif ($PsCmdlet.ParameterSetName -eq 'Script') {
            $config = Get-DBOConfig
        }
        elseif ($PsCmdlet.ParameterSetName -eq 'Pipeline') {
            $package = Get-DBOPackage -InputObject $InputObject
            $config = $package.Configuration
        }

        #Test if the selected Connection type is supported
        if (Test-DBOSupportedSystem -Type $ConnectionType) {
            #Load external libraries
            $dependencies = Get-ExternalLibrary -Type $ConnectionType
            foreach ($dPackage in $dependencies) {
                $localPackage = Get-Package -Name $dPackage.Name -MinimumVersion $dPackage.Version -ErrorAction Stop
                foreach ($dPath in $dPackage.Path) {
                    Add-Type -Path (Join-Path (Split-Path $localPackage.Source -Parent) $dPath)
                }
            }
        }
        else {
            Stop-PSFFunction -EnableException $true -Message "Prerequisites have not been met to run the deployment."
            return
        }

        #Join variables from config and parameters
        $runtimeVariables = @{ }
        if ($Variables) {
            $runtimeVariables += $Variables
        }
        if ($config.Variables) {
            foreach ($variable in $config.Variables.psobject.Properties.Name) {
                if ($variable -notin $runtimeVariables.Keys) {
                    $runtimeVariables += @{
                        $variable = $config.Variables.$variable
                    }
                }
            }
        }
    
        #Replace tokens if any
        foreach ($property in $config.psobject.Properties.Name | Where-Object { $_ -ne 'Variables' }) {
            $config.SetValue($property, (Resolve-VariableToken $config.$property $runtimeVariables))
        }
    
        #Apply overrides if any
        foreach ($key in ($PSBoundParameters.Keys | Where-Object { $_ -notin 'Variables', 'Password' })) {
            if ($key -in [DBOpsConfig]::EnumProperties()) {
                $config.SetValue($key, (Resolve-VariableToken $PSBoundParameters[$key] $runtimeVariables))
            }
        }
    
        #Apply default values if not set
        # if (!$config.ApplicationName) { $config.SetValue('ApplicationName', 'dbops') }
        # if (!$config.SqlInstance) { $config.SetValue('SqlInstance', 'localhost') }
        # if ($config.ConnectionTimeout -eq $null) { $config.SetValue('ConnectionTimeout', 30) }
        # if ($config.ExecutionTimeout -eq $null) { $config.SetValue('ExecutionTimeout', 0) }
    
        #Build connection string
        if (!$ConnectionString) {
            $CSBuilder = New-Object -TypeName System.Data.SqlClient.SqlConnectionStringBuilder
            $CSBuilder["Server"] = $config.SqlInstance
            if ($config.Database) { $CSBuilder["Database"] = $config.Database }
            if ($config.Encrypt) { $CSBuilder["Encrypt"] = $true }
            $CSBuilder["Connection Timeout"] = $config.ConnectionTimeout
        
            if ($config.Credential) {
                $CSBuilder["User ID"] = $config.Credential.UserName
                $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($config.Credential.Password)
                $CSBuilder["Password"] = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
            }
            elseif ($config.Username) {
                $CSBuilder["User ID"] = $config.UserName
                if ($Password) {
                    [SecureString]$currentPassword = $Password
                }
                else {
                    [SecureString]$currentPassword = $config.Password
                }
                $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($currentPassword)
                $CSBuilder["Password"] = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
            }
            else {
                $CSBuilder["Integrated Security"] = $true
            }
            if ($ConnectionType -eq 'SQLServer') {
                $CSBuilder["Application Name"] = $config.ApplicationName
            }
            $connString = $CSBuilder.ToString()
        }
        else {
            $connString = $ConnectionString
        }
    
        $scriptCollection = @()
        if ($PsCmdlet.ParameterSetName -ne 'Script') {
            # Get contents of the script files
            foreach ($build in $package.builds) {
                foreach ($script in $build.scripts) {
                    # Replace tokens in the scripts
                    $scriptPackagePath = ($script.GetPackagePath() -replace ('^' + [regex]::Escape($package.GetPackagePath())), '').TrimStart('\')
                    $scriptContent = Resolve-VariableToken $script.GetContent() $runtimeVariables
                    $scriptCollection += [DbUp.Engine.SqlScript]::new($scriptPackagePath, $scriptContent)
                }
            }
        }
        else {
            foreach ($scriptItem in (Get-ChildScriptItem $ScriptPath)) {
                # Replace tokens in the scripts
                $scriptContent = Resolve-VariableToken (Get-Content $scriptItem.FullName -Raw) $runtimeVariables
                $scriptCollection += [DbUp.Engine.SqlScript]::new($scriptItem.SourcePath, $scriptContent)
            }
        }

        #Build dbUp object
        $dbUp = [DbUp.DeployChanges]::To
        if ($ConnectionType -eq 'SqlServer') {
            $dbUpConnection = [DbUp.SqlServer.SqlConnectionManager]::new($connString)
            if ($config.Schema) {
                $dbUp = [SqlServerExtensions]::SqlDatabase($dbUp, $dbUpConnection, $config.Schema)
            }
            else {
                $dbUp = [SqlServerExtensions]::SqlDatabase($dbUp, $dbUpConnection)
            }
        }
        elseif ($ConnectionType -eq 'Oracle') {
            $dbUpConnection = [DbUp.Oracle.OracleConnectionManager]::new($connString)
            if ($config.Schema) {
                $dbUp = [DbUp.Oracle.OracleExtensions]::OracleDatabase($dbUpConnection, $config.Schema)
            }
            else {
                $dbUp = [DbUp.Oracle.OracleExtensions]::OracleDatabase($dbUpConnection)
            }
        }
        #Add deployment scripts to the object
        $dbUp = [StandardExtensions]::WithScripts($dbUp, $scriptCollection)

        #Disable automatic sorting by using a custom comparer
        $comparer = [DBOpsScriptComparer]::new($scriptCollection.Name)
        $dbUp = [StandardExtensions]::WithScriptNameComparer($dbUp, $comparer)

        if ($config.DeploymentMethod -eq 'SingleTransaction') {
            $dbUp = [StandardExtensions]::WithTransaction($dbUp)
        }
        elseif ($config.DeploymentMethod -eq 'TransactionPerScript') {
            $dbUp = [StandardExtensions]::WithTransactionPerScript($dbUp)
        }

        # Enable logging using dbopsConsoleLog class implementing a logging Interface
        $dbUpLog = [DBOpsLog]::new($config.Silent, $OutputFile, $Append)
        $dbUp = [StandardExtensions]::LogTo($dbUp, $dbUpLog)
        $dbUp = [StandardExtensions]::LogScriptOutput($dbUp)

        # Configure schema versioning
        if (!$config.SchemaVersionTable) {
            $dbUpTableJournal = [DbUp.Helpers.NullJournal]::new()
        }
        elseif ($config.SchemaVersionTable) {
            $table = $config.SchemaVersionTable.Split('.')
            if (($table | Measure-Object).Count -gt 2) {
                Stop-PSFFunction -EnableException $true -Message 'Incorrect table name - use the following syntax: schema.table'
                return
            }
            elseif (($table | Measure-Object).Count -eq 2) {
                $tableName = $table[1]
                $schemaName = $table[0]
            }
            elseif (($table | Measure-Object).Count -eq 1) {
                $tableName = $table[0]
                if ($config.Schema) {
                    $schemaName = $config.Schema
                }
                else {}
            }
            else {
                Stop-PSFFunction -EnableException $true -Message 'No table name specified'
                return
            }
            # Set default schema for known DB Types
            if (!$schemaName) {
                if ($ConnectionType -eq 'SqlServer') { $schemaName = 'dbo' }
            }
            #Enable schema versioning
            if ($ConnectionType -eq 'SqlServer') { $dbUpJournalType = [DbUp.SqlServer.SqlTableJournal] }
            elseif ($ConnectionType -eq 'Oracle') { $dbUpJournalType = [DbUp.Oracle.OracleTableJournal] }
            
            $dbUpTableJournal = $dbUpJournalType::new( { $dbUpConnection }, { $dbUpLog }, $schemaName, $tableName)
            
            #$dbUp = [SqlServerExtensions]::JournalToSqlTable($dbUp, $schemaName, $tableName)
        }
        $dbUp = [StandardExtensions]::JournalTo($dbUp, $dbUpTableJournal)

        #Adding execution timeout - defaults to unlimited execution
        $dbUp = [StandardExtensions]::WithExecutionTimeout($dbUp, [timespan]::FromSeconds($config.ExecutionTimeout))

        #Build and Upgrade
        if ($PSCmdlet.ShouldProcess($package, "Deploying the package")) {
            $build = $dbUp.Build()
            $upgradeResult = $build.PerformUpgrade()
            $upgradeResult
            if (!$upgradeResult.Successful) {
                #Throw output error if unsuccessful
                throw $upgradeResult.Error
            }
        }

    }
    end {}
}