Skip to content

Commit

Permalink
Import-DbaCsv - ensure the reader is closed in the inner loop (#7165)
Browse files Browse the repository at this point in the history
  • Loading branch information
lancasteradam authored Mar 11, 2021
1 parent 89a749a commit 6336ca8
Showing 1 changed file with 32 additions and 15 deletions.
47 changes: 32 additions & 15 deletions functions/Import-DbaCsv.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -644,8 +644,6 @@ function Import-DbaCsv {
Write-Progress -id 1 -activity "Inserting $resultcount rows" -status "Complete" -Completed
}

$reader.Close()
$reader.Dispose()
$completed = $true
} catch {
$completed = $false
Expand All @@ -654,14 +652,43 @@ function Import-DbaCsv {
Write-Progress -id 1 -activity "Inserting $resultcount rows" -status "Failed" -Completed
}
Stop-Function -Continue -Message "Failure" -ErrorRecord $_
} finally {
try {
$reader.Close()
$reader.Dispose()
} catch {
}

if (-not $NoTransaction) {
if ($completed) {
try {
$null = $transaction.Commit()
} catch {
}
} else {
try {
$null = $transaction.Rollback()
} catch {
}
}
}

try {
$sqlconn.Close()
$sqlconn.Dispose()
} catch {
}

try {
$bulkCopy.Close()
$bulkcopy.Dispose()
} catch {
}
}
}
if ($PSCmdlet.ShouldProcess($instance, "Finalizing import")) {
if ($completed) {
# "Note: This count does not take into consideration the number of rows actually inserted when Ignore Duplicates is set to ON."
if (-not $NoTransaction) {
$null = $transaction.Commit()
}
$rowscopied = Get-BulkRowsCopiedCount $bulkcopy
$rps = [int]($rowscopied / $elapsed.Elapsed.TotalSeconds)

Expand All @@ -684,16 +711,6 @@ function Import-DbaCsv {
return
}
}

# Close everything just in case & ignore errors
try {
$null = $sqlconn.close(); $null = $sqlconn.Dispose();
$null = $bulkCopy.close(); $bulkcopy.dispose();
$null = $reader.close(); $null = $reader.dispose()
} catch {
#here to avoid an empty catch
$null = 1
}
}
}
}
Expand Down

0 comments on commit 6336ca8

Please sign in to comment.