import re


RE_MESSAGE = re.compile(r'Message: (.+), Sqlstate:')
RE_SQLSTATE = re.compile(r'Sqlstate: (\d+)')
RE_POSITION = re.compile(r'Position: (\d+)')


def format_error(error):
    msg = str(error)
    if not hasattr(error, 'one_line_sql'):
        return msg

    result = ''

    match = RE_SQLSTATE.search(msg)
    if match:
        result += 'ERROR %s: ' % match.group(1)

    match = RE_MESSAGE.search(msg)
    if match:
        result += match.group(1)

    match = RE_POSITION.search(msg)
    if match:
        sql = error.one_line_sql()
        position = int(match.group(1))
        result += ('\n%s\n' % sql) + (' ' * (position - 1)) + '^'

    return result

@@ -582,16 +582,745 @@
 oup(1))%0A
+%0A        # Truncate the SQL query if its length %3E n (n must be odd)%0A        n = 75%0A        d = (n - 1) / 2%0A        length = len(sql)%0A        if length %3E n:%0A            left = position - d%0A            right = position + d%0A            position = d%0A            head = '...'%0A            tail = '...'%0A%0A            if left %3C 0:%0A                right -= left%0A                position += left%0A                left = 0%0A                head = ''%0A            elif right %3E= length:%0A                offset = right - length + 1%0A                left -= offset%0A                position += offset%0A                right = length - 1%0A                tail = ''%0A%0A            sql = head + sql%5Bleft:right + 1%5D + tail%0A            position += len(head)%0A%0A
         

Format error message better in a long SQL