SimplySql
SimplySql copied to clipboard
Show error position
Hi
Not an issue just some snippet of code I wanted to share.
Sometime you get an error like error at or near ".". I have 100 "." in my query, not really helpful (:
Now you can run Get-SqlQueryError after getting an error from Invoke-SqlQuery and it will show you the last query and mark the error location in red so you know which "." it is:

Probably need some refining and testing (tested it only on PostgreSQL) but maybe it can help someone
function Get-SqlQueryError {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeLine)]
[System.Management.Automation.ErrorRecord]$ErrorRecord
)
if (!$ErrorRecord) {
foreach ($ErrorI in $Error) {
if ($ErrorI.Exception.Message -like '*Exception calling "Fill"*') {
$ErrorRecord = $ErrorI
Break
}
}
}
$Query = $ErrorRecord.Exception.InnerException.Statement.SQL
$Position = $ErrorRecord.Exception.InnerException.Position
$Start = $Query.Substring(0, $Position -1)
$End = $Query.Substring($Position, $Query.Length - $Position)
'Error: {0}' -f $ErrorRecord.Exception.Message
'Position: {0}' -f $Position
"{0}`e[41m{1}`e[0m{2}" -f $Start, $Query[$Position - 1], $End
}