Skip to content

Commit a93029f

Browse files
committed
Parse square brackets as a group just like parens
- add class sql.SquareBrackets - replace group_parenthesis() with more generic group_brackets(), which groups square and round brackets, so each can contain groups of the other
1 parent 66f00a9 commit a93029f

2 files changed

Lines changed: 52 additions & 4 deletions

File tree

sqlparse/engine/grouping.py

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -277,9 +277,48 @@ def group_identifier_list(tlist):
277277
tcomma = next_
278278

279279

280-
def group_parenthesis(tlist):
281-
_group_matching(tlist, T.Punctuation, '(', T.Punctuation, ')',
282-
sql.Parenthesis)
280+
def group_brackets(tlist):
281+
"""Group parentheses () or square brackets []
282+
283+
This is just like _group_matching, but complicated by the fact that
284+
round brackets can contain square bracket groups and vice versa
285+
"""
286+
287+
if isinstance(tlist, (sql.Parenthesis, sql.SquareBrackets)):
288+
idx = 1
289+
else:
290+
idx = 0
291+
292+
# Find the first opening bracket
293+
token = tlist.token_next_match(idx, T.Punctuation, ['(', '['])
294+
295+
while token:
296+
start_val = token.value # either '(' or '['
297+
if start_val == '(':
298+
end_val = ')'
299+
group_class = sql.Parenthesis
300+
else:
301+
end_val = ']'
302+
group_class = sql.SquareBrackets
303+
304+
tidx = tlist.token_index(token)
305+
306+
# Find the corresponding closing bracket
307+
end = _find_matching(tidx, tlist, T.Punctuation, start_val,
308+
T.Punctuation, end_val)
309+
310+
if end is None:
311+
idx = tidx + 1
312+
else:
313+
group = tlist.group_tokens(group_class,
314+
tlist.tokens_between(token, end))
315+
316+
# Check for nested bracket groups within this group
317+
group_brackets(group)
318+
idx = tlist.token_index(group) + 1
319+
320+
# Find the next opening bracket
321+
token = tlist.token_next_match(idx, T.Punctuation, ['(', '['])
283322

284323

285324
def group_comments(tlist):
@@ -395,7 +434,7 @@ def align_comments(tlist):
395434
def group(tlist):
396435
for func in [
397436
group_comments,
398-
group_parenthesis,
437+
group_brackets,
399438
group_functions,
400439
group_where,
401440
group_case,

sqlparse/sql.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,15 @@ def _groupable_tokens(self):
542542
return self.tokens[1:-1]
543543

544544

545+
class SquareBrackets(TokenList):
546+
"""Tokens between square brackets"""
547+
548+
__slots__ = ('value', 'ttype', 'tokens')
549+
550+
@property
551+
def _groupable_tokens(self):
552+
return self.tokens[1:-1]
553+
545554
class Assignment(TokenList):
546555
"""An assignment like 'var := val;'"""
547556
__slots__ = ('value', 'ttype', 'tokens')

0 commit comments

Comments
 (0)