Repository navigation
Expand file tree
/
Copy patherrors.py
More file actions
162 lines (124 loc) · 4.74 KB
/
Copy patherrors.py
File metadata and controls
162 lines (124 loc) · 4.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
from __future__ import annotations
import typing as t
from enum import auto
from collections.abc import Sequence
from sqlglot.helper import AutoName
# ANSI escape codes for error formatting
ANSI_UNDERLINE = "\033[4m"
ANSI_RESET = "\033[0m"
ERROR_MESSAGE_CONTEXT_DEFAULT = 100
class ErrorLevel(AutoName):
IGNORE = auto()
"""Ignore all errors."""
WARN = auto()
"""Log all errors."""
RAISE = auto()
"""Collect all errors and raise a single exception."""
IMMEDIATE = auto()
"""Immediately raise an exception on the first error found."""
class SqlglotError(Exception):
pass
class UnsupportedError(SqlglotError):
pass
class ParseError(SqlglotError):
def __init__(
self,
message: str,
errors: list[dict[str, t.Any]] | None = None,
):
super().__init__(message)
self.errors = errors or []
@classmethod
def new(
cls,
message: str,
description: str | None = None,
line: int | None = None,
col: int | None = None,
start_context: str | None = None,
highlight: str | None = None,
end_context: str | None = None,
into_expression: str | None = None,
) -> ParseError:
return cls(
message,
[
{
"description": description,
"line": line,
"col": col,
"start_context": start_context,
"highlight": highlight,
"end_context": end_context,
"into_expression": into_expression,
}
],
)
class TokenError(SqlglotError):
pass
class OptimizeError(SqlglotError):
pass
class SchemaError(SqlglotError):
pass
class ExecuteError(SqlglotError):
pass
def highlight_sql(
sql: str,
positions: list[tuple[int, int]],
context_length: int = ERROR_MESSAGE_CONTEXT_DEFAULT,
) -> tuple[str, str, str, str]:
"""
Highlight a SQL string using ANSI codes at the given positions.
Args:
sql: The complete SQL string.
positions: List of (start, end) tuples where both start and end are inclusive 0-based
indexes. For example, to highlight "foo" in "SELECT foo", use (7, 9).
The positions will be sorted and de-duplicated if they overlap.
context_length: Number of characters to show before the first highlight and after
the last highlight.
Returns:
A tuple of (formatted_sql, start_context, highlight, end_context) where:
- formatted_sql: The SQL with ANSI underline codes applied to highlighted sections
- start_context: Plain text before the first highlight
- highlight: Plain text from the first highlight start to the last highlight end,
including any non-highlighted text in between (no ANSI)
- end_context: Plain text after the last highlight
Note:
If positions is empty, raises a ValueError.
"""
if not positions:
raise ValueError("positions must contain at least one (start, end) tuple")
start_context = ""
end_context = ""
first_highlight_start = 0
formatted_parts = []
previous_part_end = 0
sorted_positions = sorted(positions, key=lambda pos: pos[0])
if sorted_positions[0][0] > 0:
first_highlight_start = sorted_positions[0][0]
start_context = sql[max(0, first_highlight_start - context_length) : first_highlight_start]
formatted_parts.append(start_context)
previous_part_end = first_highlight_start
for start, end in sorted_positions:
highlight_start = max(start, previous_part_end)
highlight_end = end + 1
if highlight_start >= highlight_end:
continue # Skip invalid or overlapping highlights
if highlight_start > previous_part_end:
formatted_parts.append(sql[previous_part_end:highlight_start])
formatted_parts.append(f"{ANSI_UNDERLINE}{sql[highlight_start:highlight_end]}{ANSI_RESET}")
previous_part_end = highlight_end
if previous_part_end < len(sql):
end_context = sql[previous_part_end : previous_part_end + context_length]
formatted_parts.append(end_context)
formatted_sql = "".join(formatted_parts)
highlight = sql[first_highlight_start:previous_part_end]
return formatted_sql, start_context, highlight, end_context
def concat_messages(errors: Sequence[t.Any], maximum: int) -> str:
msg = [str(e) for e in errors[:maximum]]
remaining = len(errors) - maximum
if remaining > 0:
msg.append(f"... and {remaining} more")
return "\n\n".join(msg)
def merge_errors(errors: Sequence[ParseError]) -> list[dict[str, t.Any]]:
return [e_dict for error in errors for e_dict in error.errors]