Skip to content
Permalink
Browse files

Correcting connection messages and removing unused code (#6087)

Connection error messages that didn't conform to standard.
Removed return from Read-DbaTraceFile since it was to process multiple servers.
  • Loading branch information...
wsmelton committed Oct 9, 2019
1 parent a37188c commit d73670137e717f1d41d93fc83912a0232c3985d5
@@ -88,8 +88,6 @@ function Get-DbaDbCertificate {
continue
}

#Variable marked as unused by PSScriptAnalyzer
#$dbName = $db.Name
$certs = $db.Certificates

if ($null -eq $certs) {
@@ -99,7 +99,7 @@ function Get-DbaProcess {
try {
$server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
} catch {
Stop-Function -Message "Could not connect to Sql Server instance $instance : $_" -Target $instance -ErrorRecord $_ -Continue
Stop-Function -Message "Error occurred while establishing connection to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
}

$sql = "SELECT DATEDIFF(MINUTE, s.last_request_end_time, GETDATE()) AS MinutesAsleep,
@@ -1,10 +1,10 @@
function Publish-DbaDacPackage {
<#
.SYNOPSIS
The Publish-DbaDacPackage command takes a dacpac which is the output from an SSDT project and publishes it to a database. Changing the schema to match the dacpac and also to run any scripts in the dacpac (pre/post deploy scripts).
The Publish-DbaDacPackage command takes a dacpac and publishes it to a database.
.DESCRIPTION
Deploying a dacpac uses the DacFx which historically needed to be installed on a machine prior to use. In 2016 the DacFx was supplied by Microsoft as a nuget package (Microsoft.Data.Tools.MSBuild) and this uses that nuget package.
Publishes the dacpac taken from SSDT project or Export-DbaDacPackage. Changing the schema to match the dacpac and also to run any scripts in the dacpac (pre/post deploy scripts).
.PARAMETER SqlInstance
The target SQL Server instance or instances.
@@ -61,7 +61,7 @@ function Publish-DbaDacPackage {
Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
.PARAMETER DacFxPath
Path to the dac dll. If this is ommited, then the version of dac dll which is packaged with dbatools is used.
Path to the dac dll. If this is omitted, then the version of dac dll which is packaged with dbatools is used.
.NOTES
Tags: Migration, Database, Dacpac
@@ -71,6 +71,8 @@ function Publish-DbaDacPackage {
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
Deploying a dacpac uses the DacFx which historically needed to be installed on a machine prior to use. In 2016 the DacFx was supplied by Microsoft as a nuget package (Microsoft.Data.Tools.MSBuild) and this uses that nuget package.
.LINK
https://dbatools.io/Publish-DbaDacPackage
@@ -103,11 +105,6 @@ function Publish-DbaDacPackage {
PS C:\> Publish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\temp\sql2016-WideWorldImporters.dacpac -PublishXml C:\temp\sql2016-WideWorldImporters-publish.xml -GenerateDeploymentScript -ScriptOnly
Does not deploy the changes, but will generate the deployment script that would be executed against WideWorldImporters.
.EXAMPLE
PS C:\> Publish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\temp\sql2016-WideWorldImporters.dacpac -PublishXml C:\temp\sql2016-WideWorldImporters-publish.xml -GenerateDeploymentReport -ScriptOnly
Does not deploy the changes, but will generate the deployment report that would be executed against WideWorldImporters.
#>
[CmdletBinding(DefaultParameterSetName = 'Obj', SupportsShouldProcess, ConfirmImpact = 'Medium')]
param (
@@ -63,13 +63,9 @@ function Read-DbaAuditFile {
$columns = @("name", "timestamp")

if ($file -is [System.String]) {
$currentfile = $file
#Variable marked as unused by PSScriptAnalyzer
#$manualadd = $true
$currentFile = $file
} elseif ($file -is [System.IO.FileInfo]) {
$currentfile = $file.FullName
#Variable marked as unused by PSScriptAnalyzer
#$manualadd = $true
$currentFile = $file.FullName
} else {
if ($file -isnot [Microsoft.SqlServer.Management.Smo.Audit]) {
Stop-Function -Message "Unsupported file type."
@@ -81,48 +77,48 @@ function Read-DbaAuditFile {
return
}

$instance = [dbainstance]$file.ComputerName
$instance = [DbaInstanceParameter]$file.ComputerName

if ($instance.IsLocalHost) {
$currentfile = $file.FullName
$currentFile = $file.FullName
} else {
$currentfile = $file.RemoteFullName
$currentFile = $file.RemoteFullName
}
}

if (-not $Exact) {
$currentfile = $currentfile.Replace('.sqlaudit', '*.sqlaudit')
$currentFile = $currentFile.Replace('.sqlaudit', '*.sqlaudit')

if ($currentfile -notmatch "sqlaudit") {
$currentfile = "$currentfile*.sqlaudit"
if ($currentFile -notmatch "sqlaudit") {
$currentFile = "$currentFile*.sqlaudit"
}
}

$accessible = Test-Path -Path $currentfile
$accessible = Test-Path -Path $currentFile
$whoami = whoami

if (-not $accessible) {
if ($file.Status -eq "Stopped") { continue }
Stop-Function -Continue -Message "$currentfile cannot be accessed from $($env:COMPUTERNAME). Does $whoami have access?"
Stop-Function -Continue -Message "$currentFile cannot be accessed from $($env:COMPUTERNAME). Does $whoami have access?"
}

if ($raw) {
return New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentfile)
return New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentFile)
}

$enum = New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentfile)
$newcolumns = ($enum.Fields.Name | Select-Object -Unique)
$enum = New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentFile)
$newColumns = ($enum.Fields.Name | Select-Object -Unique)

$actions = ($enum.Actions.Name | Select-Object -Unique)
foreach ($action in $actions) {
$newcolumns += ($action -Split '\.')[-1]
$newColumns += ($action -Split '\.')[-1]
}

$newcolumns = $newcolumns | Sort-Object
$columns = ($columns += $newcolumns) | Select-Object -Unique
$newColumns = $newColumns | Sort-Object
$columns = ($columns += $newColumns) | Select-Object -Unique

# Make it selectable, otherwise it's a weird enumeration
foreach ($event in (New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentfile))) {
foreach ($event in (New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($currentFile))) {
$hash = [ordered]@{ }

foreach ($column in $columns) {
@@ -246,16 +246,15 @@ function Read-DbaTraceFile {
$server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
} catch {
Stop-Function -Message "Error occurred while establishing connection to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
return
}

if (Test-Bound -Parameter Path) {
$currentpath = $path
$currentPath = $path
} else {
$currentpath = $server.ConnectionContext.ExecuteScalar("Select path from sys.traces where is_default = 1")
$currentPath = $server.ConnectionContext.ExecuteScalar("SELECT path FROM sys.traces WHERE is_default = 1")
}

foreach ($file in $currentpath) {
foreach ($file in $currentPath) {
Write-Message -Level Verbose -Message "Parsing $file"

$exists = Test-DbaPath -SqlInstance $server -Path $file
@@ -265,15 +264,15 @@ function Read-DbaTraceFile {
Continue
}

$sql = "select SERVERPROPERTY('MachineName') AS ComputerName,
ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
SERVERPROPERTY('ServerName') AS SqlInstance,
* FROM [fn_trace_gettable]('$file', DEFAULT) $Where"
$sql = "SELECT SERVERPROPERTY('MachineName') AS ComputerName, ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName, SERVERPROPERTY('ServerName') AS SqlInstance, *
FROM [fn_trace_gettable]('$file', DEFAULT)
$Where"

Write-Message -Message "SQL: $sql" -Level Debug
try {
$server.Query($sql)
} catch {
Stop-Function -Message "Error returned from SQL Server: $_" -Target $server -InnerErrorRecord $_
Stop-Function -Message "Error returned from SQL Server: $instance" -Target $server -InnerErrorRecord $_
}
}
}
@@ -62,7 +62,7 @@ function Test-DbaPath {
try {
$server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
} catch {
Stop-Function -Message "Failure" -ErrorRecord $_ -Target $instance -Continue
Stop-Function -Message "Error occurred while establishing connection to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
}
$counter = [pscustomobject] @{ Value = 0 }
$groupSize = 100
@@ -4,18 +4,18 @@ Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan

Describe "$CommandName Unit Tests" -Tag 'UnitTests' {
Context "Validate parameters" {
[object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')}
[object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('WhatIf', 'confirm') }
[object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Path', 'Database', 'Login', 'Spid', 'EventClass', 'ObjectType', 'ErrorId', 'EventSequence', 'TextData', 'ApplicationName', 'ObjectName', 'Where', 'EnableException'
$knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters
It "Should only contain our specific parameters" {
(@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0
(@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0
}
}
}

Describe "$CommandName Integration Tests" -Tag "IntegrationTests" {
BeforeAll {
$configs = $script:instance1, $script:instance2 | Get-DbaSpConfigure -ConfigName DefaultTraceEnabled
$configs = $script:instance1, $script:instance2 | Get-DbaSpConfigure -Name DefaultTraceEnabled
$configs | Set-DbaSpConfigure -Value $true -WarningAction SilentlyContinue
}
AfterAll {
@@ -28,8 +28,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" {

Context "Verifying command output" {
It "returns results" {
$results = $script:instance1, $script:instance2 | Get-DbaTrace -Id 1 | Read-DbaTraceFile

$results = Get-DbaTrace -SqlInstance $script:instance2 -Id 1 | Read-DbaTraceFile
$results.DatabaseName.Count | Should -BeGreaterThan 0
}

@@ -42,42 +41,23 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" {
and ApplicationName not like 'SQLAgent%'
and ApplicationName not like 'Microsoft SQL Server Management Studio%'"

# Collect the results into a variable so that the bulk import is supafast
$results = $script:instance1, $script:instance2 | Get-DbaTrace -Id 1 | Read-DbaTraceFile -Where $where -WarningAction SilentlyContinue -WarningVariable warn
# Collect the results into a variable so that the bulk import is super fast
Get-DbaTrace -SqlInstance $script:instance2 -Id 1 | Read-DbaTraceFile -Where $where -WarningAction SilentlyContinue -WarningVariable warn > $null
$warn | Should -Be $null
}
}
Context "Verify Parameter Use" {

It "Should execute using paramters Database, Login, Spid" {
$results = $script:instance1, $script:instance2 | Get-DbaTrace -Id 1 | Read-DbaTraceFile -Database Master -Login sa -Spid 7 -WarningAction SilentlyContinue -WarningVariable warn
It "Should execute using parameters Database, Login, Spid" {
$results = Get-DbaTrace -SqlInstance $script:instance2 -Id 1 | Read-DbaTraceFile -Database Master -Login sa -Spid 7 -WarningAction SilentlyContinue -WarningVariable warn
$warn | Should -Be $null
}
It "Should execute using paramters EventClass, ObjectType, ErrorId" {
$results = $script:instance1, $script:instance2 | Get-DbaTrace -Id 1 | Read-DbaTraceFile -EventClass 4 -ObjectType 4 -ErrorId 4 -WarningAction SilentlyContinue -WarningVariable warn
It "Should execute using parameters EventClass, ObjectType, ErrorId" {
$results = Get-DbaTrace -SqlInstance $script:instance2 -Id 1 | Read-DbaTraceFile -EventClass 4 -ObjectType 4 -ErrorId 4 -WarningAction SilentlyContinue -WarningVariable warn
$warn | Should -Be $null
}
It "Should execute using paramters EventSequence, TextData, ApplicationName, ObjectName" {
$results = $script:instance1, $script:instance2 | Get-DbaTrace -Id 1 | Read-DbaTraceFile -EventSequence 4 -TextData "Text" -ApplicationName "Application" -ObjectName "Name" -WarningAction SilentlyContinue -WarningVariable warn
It "Should execute using parameters EventSequence, TextData, ApplicationName, ObjectName" {
$results = Get-DbaTrace -SqlInstance $script:instance2 -Id 1 | Read-DbaTraceFile -EventSequence 4 -TextData "Text" -ApplicationName "Application" -ObjectName "Name" -WarningAction SilentlyContinue -WarningVariable warn
$warn | Should -Be $null
}

}
Context "Verify Failure with Mocks" {
It "Should Fail Connection to SqlInstance" {
mock Connect-SqlInstance {throw} -module dbatools
mock Stop-Function {"Failure"} -module dbatools
(Read-DbaTraceFile -SqlInstance "NotAnInstance" ) | Should -be "Failure"
}
It "Should try `$CurrentPath" {
#This mock forces line 257 to be tested
mock Test-Bound {$false} -module dbatools
(Read-DbaTraceFile -SqlInstance "$script:Instance2" ) | Should -Not -Be $null
}
It "Should Fail to find the Path" {
mock Test-DbaPath {$false} -module dbatools
mock Write-Message {"Path Does Not Exist"} -module dbatools
(Read-DbaTraceFile -SqlInstance "$script:Instance2" ) | Should -Be "Failure"
}
}
}

0 comments on commit d736701

Please sign in to comment.
You can’t perform that action at this time.