-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathParamParser.psm1
More file actions
532 lines (484 loc) · 22.7 KB
/
ParamParser.psm1
File metadata and controls
532 lines (484 loc) · 22.7 KB
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
#region classes
class Visitor: Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragmentVisitor
{
$Results = [System.Collections.ArrayList]@();
$ProcedureStatements = @("CreateOrAlterProcedureStatement",
"CreateProcedureStatement", "AlterProcedureStatement");
$FunctionStatements = @("CreateOrAlterFunctionStatement",
"CreateFunctionStatement", "AlterFunctionStatement");
$ModuleTokenTypes = (@("ProcedureParameter", "ProcedureReference"));
$CommentTokenTypes = (@("MultilineComment", "SingleLineComment"));
[PSCustomObject]GetResultObject ([string]$StatementType) {
return ([PSCustomObject]@{
Id = $this.Counter
ModuleId = $this.ModuleId
ObjectName = $this.ObjectName
StatementType = $StatementType
ParamId = $this.ParamId
ParamName = [string]::Empty
DataType = [string]::Empty
DefaultValue = [string]::Empty
IsOutput = $false
IsReadOnly = $false
Source = [string]::Empty
})
}
hidden [int]$Counter = 0;
hidden [int]$ModuleId = 0;
hidden [int]$ParamId = 1;
hidden [string]$Source = [string]::Empty
[void]Visit ([Microsoft.SqlServer.TransactSql.ScriptDom.TSqlFragment] $fragment)
{
$fragmentType = $fragment.GetType().Name;
# if this is an injected PRINT statement, it contains the source for this statement
if ($fragmentType -eq "StringLiteral")
{
$token = $fragment.ScriptTokenStream[$fragment.FirstTokenIndex]
if ($token.Text -like "'ParamParser.Source*")
{
$this.Source = $token.Text.Substring(21, $token.Text.Length-22)
}
}
if ($fragmentType -iin ($this.ProcedureStatements + $this.FunctionStatements + $this.ModuleTokenTypes))
{
$result = $this.GetResultObject($fragmentType);
# if body of procedure or function, increase the module # and reset param count
if ($fragmentType -iin ($this.ProcedureStatements + $this.FunctionStatements))
{
$this.ModuleId++;
$this.ParamId = 1;
$result.ParamId = $null;
$result.IsOutput = $null;
$result.IsReadOnly = $null;
$result.Source = $this.Source;
}
# for any parameter or procedure name, need to loop through all the tokens
# in the fragment to build up the name, data type, default, etc.
if ($fragmentType -iin $this.ModuleTokenTypes)
{
$seenEquals = $false;
$isOutputOrReadOnly = $false;
for ($i = $fragment.FirstTokenIndex; $i -le $fragment.LastTokenIndex; $i++)
{
$token = $fragment.ScriptTokenStream[$i];
if ($token.TokenType -notin (@("As") + $this.CommentTokenTypes))
{
if ($fragmentType -eq "ProcedureParameter")
{
if ($token.TokenType -eq "Identifier" -and ($token.Text -iin ("OUT", "OUTPUT", "READONLY")))
{
$isOutputOrReadOnly = $true;
if ($token.Text -ieq "READONLY")
{
$result.IsReadOnly = $true;
}
else
{
$result.IsOutput = $true;
}
}
if (!$seenEquals)
{
if ($token.TokenType -eq "EqualsSign")
{
$seenEquals = $true;
}
else
{
if ($token.TokenType -eq "Variable")
{
$this.ParamId++;
$result.ParamName = $token.Text;
}
else
{
if (!$isOutputOrReadOnly)
{
$result.DataType += $token.Text;
}
}
}
}
else
{
if ($token.TokenType -ne "EqualsSign" -and !$isOutputOrReadOnly)
{
$result.DefaultValue += $token.Text;
}
}
}
else
{
$result.ObjectName += $token.Text.Trim();
}
}
}
}
# tedious: need to loop through function to build the object name
# no FunctionReference but there will be multiple identifiers
if ($fragmentType -iin ($this.FunctionStatements))
{
$seenObject = $false;
$seenEndOfFirstObject = $false;
for ($i = $fragment.FirstTokenIndex; $i -le $fragment.LastTokenIndex; $i++)
{
$token = $fragment.ScriptTokenStream[$i];
if ($token.TokenType -notin (@("WhiteSpace") + $this.CommentTokenTypes))
{
if ($seenObject -and $token.TokenType -notin ("Dot","Identifier","QuotedIdentifier"))
{
$seenEndOfFirstObject = $true;
}
if ($token.TokenType -in ("Dot","Identifier","QuotedIdentifier") -and !$seenEndOfFirstObject)
{
$seenObject = $true;
$result.ObjectName += $token.Text.Trim();
}
}
}
}
$result.DataType = $result.DataType.TrimStart();
$result.DefaultValue = $result.DefaultValue.TrimStart();
$this.Results.Add($result);
$this.Counter++;
}
}
}
#endregion
#region functions
<#
.SYNOPSIS
.DESCRIPTION
Long description
.PARAMETER Script
Parameter description
.PARAMETER File
Parameter description
.PARAMETER Directory
Parameter description
.PARAMETER ServerInstance
Parameter description
.PARAMETER Database
Parameter description
.PARAMETER AuthenticationMode
Parameter description
.PARAMETER GridView
Parameter description
.PARAMETER Console
Parameter description
.PARAMETER LogToDatabase
Parameter description
.PARAMETER LogToDBAuthenticationMode
Parameter description
.EXAMPLE
$password = ConvertTo-SecureString -AsPlainText -Force -String 'secret123'
$creds = New-Object -TypeName PSCredential -ArgumentList 'myUsername', $password
Get-ParsedParams -ServerInstance "localhost" -Database "msdb" -AuthenticationMode SQL -SqlCredential $creds
.EXAMPLE
Get-ParsedParams -ServerInstance "localhost" -Database "msdb" -AuthenticationMode SQL -SqlCredential (Get-Credential -Username 'myUsername')
.NOTES
General notes
#>
Function Get-ParsedParams
{
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory = $true, ParameterSetName = "Script")]
[ValidateNotNullOrEmpty()]
[string]$Script,
[Parameter(Position = 0, Mandatory = $true, ParameterSetName = "File")]
[ValidateScript({$PSItem | ForEach-Object {
((Test-Path $_ -PathType Leaf) -and ([System.IO.Path]::GetExtension($_) -ieq ".sql"))
}
})]
[string[]]$File,
[Parameter(Position = 0, Mandatory = $true, ParameterSetName = "Directory")]
[ValidateScript({$PSItem | ForEach-Object {
(Test-Path $_ -PathType Container)
}
})]
[string[]]$Directory,
[Parameter(Position = 0, Mandatory = $true, ParameterSetName = "SQLServer")]
[ValidateNotNullOrEmpty()]
[string[]]$ServerInstance,
[Parameter(Position = 1, Mandatory = $true, ParameterSetName = "SQLServer")]
[ValidateNotNullOrEmpty()]
[string[]]$Database,
[Parameter(Position = 2, Mandatory = $false, ParameterSetName = "SQLServer")]
[ValidateSet("SQL", "Windows")]
[string]$AuthenticationMode = "Windows",
[Parameter(Position = 3, Mandatory = $false)]
[switch]$GridView,
[Parameter(Position = 4, Mandatory = $false)]
[switch]$Console, # currently logs to console whether you like it or not
[Parameter(Position = 5, Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[switch]$LogToDatabase,
[Parameter(Position = 6, Mandatory = $false)]
[ValidateSet("SQL", "Windows")]
[string]$LogToDBAuthenticationMode = "Windows"
)
#region dynamic params
DynamicParam {
$runtimeDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# here we inject a dynamic parameter based on whether SQL auth was specified or not.
# we use a PSCredential object and set to mandatory. If the user doesn't supply, this has the nice
# behavior of prompting them with a nice dialog box
if ($AuthenticationMode -eq "SQL") {
$parameterName = 'SqlCredential'
$attributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$paramAttribute = New-Object System.Management.Automation.ParameterAttribute
$paramAttribute.Mandatory = $true
$paramAttribute.Position = 7
$attributeCollection.Add($paramAttribute)
$validateAttribute = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
$attributeCollection.Add($validateAttribute)
$runtimeParam = New-Object System.Management.Automation.RuntimeDefinedParameter($parameterName, [PSCredential], $attributeCollection)
$runtimeDictionary.Add($parameterName, $runtimeParam)
}
# we also inject the requirements for the logto database and instance
if ($LogToDatabase.IsPresent) {
$parameterName = 'LogToDBServerInstance'
$attributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$paramAttribute = New-Object System.Management.Automation.ParameterAttribute
$paramAttribute.Mandatory = $true
$paramAttribute.Position = 8
$attributeCollection.Add($paramAttribute)
$validateAttribute = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
$attributeCollection.Add($validateAttribute)
$runtimeParam = New-Object System.Management.Automation.RuntimeDefinedParameter($parameterName, [string], $attributeCollection)
$runtimeDictionary.Add($parameterName, $runtimeParam)
$parameterName = 'LogToDBDatabase'
$attributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$paramAttribute = New-Object System.Management.Automation.ParameterAttribute
$paramAttribute.Mandatory = $true
$paramAttribute.Position = 9
$attributeCollection.Add($paramAttribute)
$validateAttribute = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
$attributeCollection.Add($validateAttribute)
$runtimeParam = New-Object System.Management.Automation.RuntimeDefinedParameter($parameterName, [string], $attributeCollection)
$runtimeDictionary.Add($parameterName, $runtimeParam)
}
# below we force credential input for database based login but only if mode is SQL
if ($LogToDatabase.IsPresent -and $LogToDBAuthenticationMode -eq "SQL") {
$parameterName = 'LogToDBSqlCredential'
$attributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$paramAttribute = New-Object System.Management.Automation.ParameterAttribute
$paramAttribute.Mandatory = $true
$paramAttribute.Position = 10
$attributeCollection.Add($paramAttribute)
$validateAttribute = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
$attributeCollection.Add($validateAttribute)
$runtimeParam = New-Object System.Management.Automation.RuntimeDefinedParameter($parameterName, [PSCredential], $attributeCollection)
$runtimeDictionary.Add($parameterName, $runtimeParam)
}
return $runtimeDictionary
}
#endregion
begin {
# bind the dynamic params to expected var names
$SqlCredential = $PSBoundParameters["SqlCredential"]
$LogToDBServerInstance = $PSBoundParameters["LogToDBServerInstance"]
$LogToDBDatabase = $PSBoundParameters["LogToDBDatabase"]
$LogToDBSqlCredential = $PSBoundParameters["LogToDBSqlCredential"]
$parser = [Microsoft.SqlServer.TransactSql.ScriptDom.TSql150Parser]($true)::New();
$errors = [System.Collections.Generic.List[Microsoft.SqlServer.TransactSql.ScriptDom.ParseError]]::New();
# if user called with script data, nothing to do... otherwise we need to preprocess into common format
switch ($psCmdlet.ParameterSetName) {
"File" {
foreach ($item in $File) {
$data = (Get-Content -Path $item -Raw)
$Script += ("PRINT 'ParamParser.Source: $($item)'`nGO`n`n$($data)`nGO`n`n" )
}
}
"Directory" {
foreach ($item in $Directory) {
Get-ChildItem -Path $item -Filter "*.sql" -Recurse | ForEach-Object {
$data = (Get-Content -Path $_.FullName -Raw)
$Script += ("PRINT 'ParamParser.Source: $($_.FullName)'`nGO`n`n$($data)`nGO`n`n" )
}
}
}
"SQLServer" {
$connectionParams = @{
AuthMode = $AuthenticationMode
}
if ($SqlCredential) {
$connectionParams.SqlCredential = $SqlCredential
}
foreach ($ServerInstanceName in $ServerInstance) {
$connectionParams.ServerInstance = $ServerInstanceName
foreach ($DatabaseName in $Database) {
$connectionParams.Database = $DatabaseName
$Connection = Get-DBConnection @connectionParams
try {
$Connection.Open()
$Command = $Connection.CreateCommand()
$Command.CommandText = @"
SELECT script = OBJECT_DEFINITION(object_id)
FROM sys.objects
WHERE type IN (N'P',N'IF',N'FN',N'TF');
"@
$Reader = $Command.ExecuteReader()
while ($Reader.Read()) {
$Data = $Reader.GetValue(0).ToString()
$Script += ("PRINT 'ParamParser.Source: [$($ServerInstanceName)].[$($DatabaseName)]'`nGO`n`n$($data)`nGO`n`n" )
}
}
catch {
Write-Host "Database connection failed ($($ServerInstanceName), $($DatabaseName)).`n$PSItem" -ForegroundColor Yellow
}
finally {
$Connection.Close()
}
}
}
}
}
}
process {
$fragment = $parser.Parse([System.IO.StringReader]::New($Script), [ref]$errors);
if ($errors.Count -gt 0) {
throw "$($errors.Count) parsing error(s): $(($errors | ConvertTo-Json))";
}
$visitor = [Visitor]::New();
$fragment.Accept($visitor);
# collapse rows and correct ModuleId assignments
$idsToExclude = @();
for ($i = 1; $i -le $visitor.Results.Count; $i++) {
$thisObject = $visitor.Results[$i];
$prevObject = $visitor.Results[$i-1];
if ($prevObject.ModuleId -eq 0) { $prevObject.ModuleId = 1 }
if ($visitor.ProcedureStatements -icontains $prevObject.StatementType -and
$prevObject.ModuleId -eq $thisObject.ModuleId) {
$prevObject.ObjectName = $thisObject.ObjectName;
$idsToExclude += $i;
}
if ($thisObject.StatementType -eq "ProcedureReference") {
if ($visitor.ProcedureStatements -icontains $prevObject.StatementType) {
$prevObject.ObjectName = $thisObject.ObjectName;
}
$idsToExclude += $i;
}
if (($visitor.ProcedureStatements + $visitor.FunctionStatements) -icontains $prevObject.StatementType) {
$prevObject.ModuleId = $thisObject.ModuleId
}
}
}
end {
if (($GridView -eq $false -and $LogToDatabase -eq $false) -or ($Console -eq $true)) {
# list all properties for all *important* fragments - longer output:
Write-Output ($visitor.Results) | Where-Object {$_.Id -notin $idsToExclude};
}
if ($GridView -eq $true) {
# spawn a new GridView window instead, much more concise:
$visitor.Results | Where-Object {$_.Id -notin $idsToExclude} | Out-GridView -Title "ParamParser Output"
}
if ($LogToDatabase -eq $true) {
# log to database -- requires database-side objects to be created
# see .\database\DatabaseSupportObjects.sql
$connectionParams = @{
ServerInstance = $LogToDBServerInstance
Database = $LogToDBDatabase
AuthMode = $LogToDBAuthenticationMode
}
if ($LogToDBSqlCredential) {
$connectionParams.SqlCredential = $LogToDBSqlCredential
}
$WriteConnection = Get-DBConnection @connectionParams
try {
$WriteConnection.Open()
$WriteCommand = $WriteConnection.CreateCommand()
$WriteCommand.CommandType = [System.Data.CommandType]::StoredProcedure
$WriteCommand.CommandText = "dbo.LogParameters"
$dt = New-Object System.Data.DataTable;
$dt.Columns.Add("ModuleId", [int]) > $null
$dt.Columns.Add("ObjectName", [string]) > $null
$dt.Columns.Add("StatementType", [string]) > $null
$dt.Columns.Add("ParamId", [int]) > $null
$dt.Columns.Add("ParamName", [string]) > $null
$dt.Columns.Add("DataType", [string]) > $null
$dt.Columns.Add("DefaultValue", [string]) > $null
$dt.Columns.Add("IsOutput", [System.Boolean]) > $null
$dt.Columns.Add("IsReadOnly", [System.Boolean]) > $null
$dt.Columns.Add("Source", [string]) > $null
$visitor.Results | Where-Object Id -notin $idsToExclude | ForEach-Object {
$dr = $dt.NewRow()
$dr.ModuleId = $_.ModuleId
$dr.ObjectName = $_.ObjectName
$dr.StatementType = $_.StatementType
if ($null -ne $_.ParamId) {
$dr.ParamId = $_.ParamId
}
$dr.ParamName = $_.ParamName
$dr.DataType = $_.DataType
$dr.DefaultValue = $_.DefaultValue
if ($null -ne $_.IsOutput) {
$dr.IsOutput = $_.IsOutput
}
if ($null -ne $_.IsReadOnly) {
$dr.IsReadOnly = $_.IsReadOnly
}
$dr.Source = $_.Source
$dt.Rows.Add($dr) > $null
}
$tvp = New-Object System.Data.SqlClient.SqlParameter
$tvp.ParameterName = "ParameterSet"
$tvp.SqlDBtype = [System.Data.SqlDbType]::Structured
$tvp.Value = $dt
$WriteCommand.Parameters.Add($tvp) > $null
try {
$WriteCommand.ExecuteNonQuery() > $null
Write-Host "Wrote to database successfully." -ForegroundColor Green
}
catch {
Write-Host "Database write failed. $PSItem" -ForegroundColor Yellow
}
finally {
$WriteConnection.Close()
}
}
catch {
Write-Host "Write database connection failed ($($LogToDBServerInstance), $($LogToDBDatabase))`n$PSItem." -ForegroundColor Yellow
}
}
}
}
Function Get-DBConnection
{
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ServerInstance,
[Parameter(Position = 1, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Database,
[Parameter(Position = 2, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$AuthMode,
[Parameter(Position = 3, Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[PSCredential]$SqlCredential
)
begin {
$Conn = New-Object System.Data.SqlClient.SqlConnection
$ConnectionString = "Server=$($ServerInstance); Database=$($Database);"
if ($AuthMode -eq "SQL" -and $null -eq $SqlCredential) {
throw "You must supply SqlCredential parameter if using SQL authentication mode."
}
if ($AuthMode -eq "SQL") {
$ConnectionString += "User ID=$($SqlCredential.UserName); Password=$($SqlCredential.GetNetworkCredential().Password);"
}
if ($AuthMode -eq "Windows") {
$ConnectionString += "Trusted_Connection=Yes; Integrated Security=SSPI;"
}
}
process {
$Conn.ConnectionString = $ConnectionString;
}
end {
return $Conn
}
}
#endregion