SimplySql icon indicating copy to clipboard operation
SimplySql copied to clipboard

Show error position

Open ili101 opened this issue 5 years ago • 0 comments

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: image

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
}

ili101 avatar Jul 30 '20 15:07 ili101