Functions/ProductivityTools.PSDbUp.NewDbUpMigration.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
function GetLastScriptNumer
{
    [cmdletbinding()]
    param (
    [Parameter(Mandatory=$false)]
    [string]$Path)

    $sqls=@(Get-ChildItem -Path $Path -Filter '*.sql')
    $maximumNumber=99999
    foreach($sql in $sqls)
    {
        $name=$sql.BaseName
        $numberString=$name.SubString(0,5)
        $number=[convert]::ToInt32($numberString, 10)
        
        if($number -lt $maximumNumber)
        {
            $maximumNumber=$number
        }
    }

    Write-Verbose "Last number of the script is $number"
    return $number
}

function GenerateScriptName
{
    [cmdletbinding()]
    param (
    [Parameter(Mandatory=$true)]
    [int]$LastNumber,
    
    [Parameter(Mandatory=$true)]
    [string]$Name
    )
    
    $nextNumer=$LastNumber+1
    $resultName=$nextNumer.ToString().PadLeft(5,'0')+'.'+$Name+'.sql'
    
    Write-Verbose "Next name for the script is $resultName"
    return $resultName
}


function New-DbUpMigration{
    [cmdletbinding()]
    param (
    [Parameter(Mandatory=$true)]
    [string]$Name, 
    
    [Parameter(Mandatory=$true)]
    [string]$Content, 

    [Parameter(Mandatory=$false)]
    [string]$Path)

    Write-Verbose "Create-Migration started"
    
    if ($Path -eq '')
    {
        $Path=Get-Location
    }

    $lastScriptNumber=GetLastScriptNumer $Path
    $nextScriptName=GenerateScriptName $lastScriptNumber $Name
    
    
    New-Item -Path $Path -Name $nextScriptName -ItemType File -Value $Content |Out-Null
}