Split-SqlScript.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
<#
.SYNOPSIS
Scans a (list of) T-SQL script files(s) and returns information about the operations being performed by them.
 
.DESCRIPTION
This function utilizes the SQL Server ScriptDom Parser object to parse and return information about each batch and statements within each batch
of T-SQL commands they contain. It will return an object that contains high-level information, as well as a batches object which in turn contains
statement objects.
 
.PARAMETER File
The [System.IO.FileInfo] object containing the files you want to scan. This type of object is usually returned from a Get-ChildItem cmdlet, so you can pipe the
results of it to this function. Otherwise you can just use full file names. Required.
 
.PARAMETER Script
A string that contains a script to parse.
 
.PARAMETER UseQuotedIdentifier
Whether or not the quoted identifier option is turned on for the parser. Defaults to true and is passed to the object instantiation.
 
.NOTES
Out-of-the-box this function will search for:
    - DML statements (INSERT, UPDATE, DELETE)
    - Certain DDL Statements:
    - ALTER TABLE
    - DROP INDEX
    - CREATE INDEX
    - CREATE PROCEDURE
    - DROP PROCEDURE
    - EXEC
 
You can extend the tests by adding a new [ParserKey] object to the $ParserKeys array. For now, these defined tests live in the code
but I expect them to be an external json file at some point.
 
Author: Drew Furgiuele (@pittfurg, port1433.com)
Tags: T-SQL, Parser
 
.LINK
 
.EXAMPLE
$Results = Get-ChildItem -Path C:\Scripts | Split-SqlScript
 
Execute the parser against a list of files returned from the Get-ChildItem cmdlet and store the returned object in the $Results variable
 
#>

function Split-SqlScript {
    [cmdletbinding()]
    param (
        [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [Parameter(ParameterSetName="File", Mandatory)]
        [Alias("FullName")]
        [string] $File,

        [Parameter(ParameterSetName="Script", Mandatory)]
        [string] $Script,

        [string] $UseQuotedIdentifier = $true
    )

    begin {
        $pathToScriptDomLibrary = Join-Path (Get-Module SqlServer -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1 -ExpandProperty ModuleBase) Microsoft.SqlServer.TransactSql.ScriptDom.dll

        $ParserKeys = @()

        Class ParserKey {
            [string] $ObjectType
            [string] $SchemaSpecification
            ParserKey ([string] $ObjectType, [string] $SchemaSpecification) {
                $this.ObjectType = $ObjectType
                $this.SchemaSpecification = $SchemaSpecification
            }
        }

        $ParserKeys += New-Object Parserkey ("SelectStatement", "Queryexpression.Fromclause.Tablereferences.Schemaobject")
        $ParserKeys += New-Object Parserkey ("InsertStatement", "InsertSpecification.Target.SchemaObject")
        $ParserKeys += New-Object Parserkey ("UpdateStatement", "UpdateSpecification.Target.SchemaObject")
        $ParserKeys += New-Object Parserkey ("DeleteStatement", "DeleteSpecification.Target.SchemaObject")
        $ParserKeys += New-Object Parserkey ("AlterTableAddTableElementStatement", "SchemaObjectName")
        $ParserKeys += New-Object Parserkey ("AlterTableDropTableElementStatement", "SchemaObjectName")
        $ParserKeys += New-Object Parserkey ("DropIndexStatement", "DropIndexClauses.Object")
        $ParserKeys += New-Object Parserkey ("CreateIndexStatement", "OnName")
        $ParserKeys += New-Object Parserkey ("CreateProcedureStatement", "ProcedureReference.Name")
        $ParserKeys += New-Object Parserkey ("AlterProcedureStatement", "ProcedureReference.Name")
        $ParserKeys += New-Object Parserkey ("CreateFunctionStatement", "Name")
        $ParserKeys += New-Object Parserkey ("AlterFunctionStatement", "Name")
        $ParserKeys += New-Object Parserkey ("CreateTableStatement", "SchemaObjectName")
        $ParserKeys += New-Object Parserkey ("DropProcedureStatement", "Objects")
        $ParserKeys += New-Object Parserkey ("DropTableStatement", "Objects")
        $ParserKeys += New-Object Parserkey ("PredicateSetStatement", "Options")
        $ParserKeys += New-Object Parserkey ("GrantStatement", "Objects")
        $ParserKeys += New-Object Parserkey ("ExecuteStatement", "ExecuteSpecification.ExecutableEntity.ProcedureReference.ProcedureReference.Name")
        $ParserKeys += New-Object Parserkey ("DeclareVariableStatement", $null)
        $ParserKeys += New-Object Parserkey ("PrintStatement", $null)
        $ParserKeys += New-Object Parserkey ("CreateLoginStatement", $null)

        $LibraryLoaded = $false
        $ObjectCreated = $false
        $LibraryVersions = @(14, 13, 12, 11)

        if ($pathToScriptDomLibrary -ne "") {
            try {
                Add-Type -Path $pathToScriptDomLibrary -ErrorAction SilentlyContinue
                Write-Verbose "Loaded library from path $pathToScriptDomLibrary"
            } catch {
                throw "Couldn't load the required ScriptDom library from the path specified!"
            }
        } else {
            ForEach ($v in $LibraryVersions) {
                if (!$LibraryLoaded) {
                    try {
                        Add-Type -AssemblyName "Microsoft.SqlServer.TransactSql.ScriptDom,Version=$v.0.0.0,Culture=neutral,PublicKeyToken=89845dcd8080cc91"  -ErrorAction SilentlyContinue
                        Write-Verbose "Loaded version $v.0.0.0 of the ScriptDom library."
                        $LibraryLoaded = $true
                    } catch {
                        Write-Verbose "Couldn't load version $v.0.0.0 of the ScriptDom library."
                    }
                }
            }
        }

        ForEach ($v in $LibraryVersions) {
            if (!$ObjectCreated) {
                try {
                    $ParserNameSpace = "Microsoft.SqlServer.TransactSql.ScriptDom.TSql" + $v + "0Parser"
                    $Parser = New-Object $ParserNameSpace($UseQuotedIdentifier)
                    $ObjectCreated = $true
                    Write-Verbose "Created parser object for version $v..."
                } catch {
                    Write-Verbose "Couldn't load version $v.0.0.0 of the ScriptDom library."
                }
            }
        }

        if (!$ObjectCreated) {
            throw "Unable to create ScriptDom library; did you load the right version of the library?"
        }

    }


    process {
        if ($PSCmdlet.ParameterSetName -eq "File") {
            $currentFileName = Resolve-Path $File
            $scriptName = Split-Path -Leaf $currentFileName
            Write-Verbose "Parsing $currentFileName..."
            $Reader = New-Object System.IO.StreamReader($currentFileName)
        } else {
            $currentFileName = $null
            $scriptName = $null
            $Reader = New-Object System.IO.StringReader($Script)
        }

        $Errors = $null
        $Fragment = $Parser.Parse($Reader, [ref] $Errors)

        [bool] $HasErrors = $false
        if ($null -ne $Errors) {
            [bool] $HasErrors = $true
        }

        $ScriptObject = [PSCustomObject] @{
            PSTypeName      = "Parser.DOM.Script"
            ScriptName      = $scriptName
            ScriptFilePath  = $currentFileName
            NumberOfBatches = $Fragment.Batches.Count
            HasParseErrors  = $HasErrors
            Errors          = $Errors
            Batches         = @()
        }

        Add-Member -InputObject $ScriptObject -Type ScriptMethod -Name ToString -Value { $this.psobject.typenames[0] } -Force

        $TotalBatches = 0
        ForEach ($b in $Fragment.Batches) {
            $TotalBatches++;

            $BatchObject = [pscustomobject] @{
                PSTypeName  = "Parser.DOM.Batch"
                ScriptName  = $scriptName
                BatchNumber = $TotalBatches
                Statements  = @()
            }

            Add-Member -InputObject $BatchObject -Type ScriptMethod -Name ToString -Value { $this.psobject.typenames[0] } -Force

            $TotalStatements = 0
            ForEach ($s in $b.Statements) {
                $TotalStatements++
                $StatementObject = Get-Statement $s $ParserKeys $scriptName

                $BatchObject.Statements += $StatementObject
            }
            $ScriptObject.Batches += $BatchObject
        }

        $Reader.Close()

        $ScriptObject
    }

    end {
        $Reader.Dispose()
    }
}