Functions/ProductivityTools.PSDbUp.InvokeDbUpMigration.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
function LibPath()
{
    $path="$PSScriptRoot\lib\"
    return $path
}

function DbUpDlls()
{
    $libPath=LibPath
    $path=$libPath+"dbup-sqlserver.dll"
    Write-Verbose "DbUp dlls are taken from following path: $path"
    return $path
}


function PerformDbUp()
{
    [cmdletbinding()]
    param ([string]$SqlInstance, [string]$DatabaseName, [string]$SchemaName, $path)

    New-SqlSchema -SqlInstance $SqlInstance -DatabaseName $DatabaseName -SchemaName $SchemaName
    
    $dbUpDlls=DbUpDlls
    Add-Type -Path $dbUpDlls
    
    $connectionstring="Server=$SqlInstance;database=$DatabaseName;Trusted_Connection=Yes;Connection Timeout=10;"
    Write-Verbose "Follwing connection string will be used: $connectionstring"
    
    $dbUp = [DbUp.DeployChanges]::To
    $dbUp = [SqlServerExtensions]::SqlDatabase($dbUp, $connectionstring)
    $dbUp = [StandardExtensions]::WithScriptsFromFileSystem($dbUp, $path)
    $dbUp = [SqlServerExtensions]::JournalToSqlTable($dbUp, "$SchemaName", 'DbUp')
    $dbUp = [StandardExtensions]::LogToConsole($dbUp)
    $upgradeResult = $dbUp.Build().PerformUpgrade()


    $scripts=$upgradeResult.Scripts
    if ($upgradeResult.Successful)
    {
        Write-Host Success -ForegroundColor Green
    }
    
    $result=$upgradeResult
    $resultJson=ConvertTo-Json $result
    Write-Verbose $resultJson
}



function Invoke-DbUpMigration {
    [cmdletbinding()]
    param (
    [Parameter(Mandatory=$true)]
    [string]$SqlInstance, 
    
    [Parameter(Mandatory=$true)]
    [string]$DatabaseName, 
    
    [Parameter(Mandatory=$false)]
    [string]$SchemaName='dbo', 
    
    [Parameter(Mandatory=$false)]
    [string]$Path    
    )

    Write-Verbose "Invoke-DbUp started"
    
    if ($Path -eq '')
    {
        $Path=Get-Location
    }
    
    Write-Verbose "Scripts will be taken from $Path"
    
    New-SqlSchema -DatabaseName $DatabaseName -SqlInstance $SqlInstance -SchemaName $SchemaName -Verbose:$VerbosePreference
    PerformDbUp $SqlInstance $DatabaseName $SchemaName $Path 
    Write-Verbose "finished"
}