Skip to content

Commit cb2cf7a

Browse files
authored
fix(parser):adapt order by has parentheses (#32)
1 parent 55a31f9 commit cb2cf7a

File tree

3 files changed

+23
-6
lines changed

3 files changed

+23
-6
lines changed

parser/mysql_parser/parser.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -350,9 +350,14 @@ def p_sort_items(p):
350350

351351

352352
def p_sort_item(p):
353-
r"""sort_item : value_expression order_opt null_ordering_opt"""
354-
p[0] = SortItem(p.lineno(1), p.lexpos(1),
355-
sort_key=p[1], ordering=p[2] or 'asc', null_ordering=p[3])
353+
r"""sort_item : value_expression order_opt null_ordering_opt
354+
| LPAREN value_expression RPAREN order_opt null_ordering_opt"""
355+
if len(p) == 4:
356+
p[0] = SortItem(p.lineno(1), p.lexpos(1),
357+
sort_key=p[1], ordering=p[2] or 'asc', null_ordering=p[3])
358+
else:
359+
p[0] = SortItem(p.lineno(1), p.lexpos(1),
360+
sort_key=p[2], ordering=p[4] or 'asc', null_ordering=p[5])
356361

357362

358363
def p_order_opt(p):

parser/oceanbase_parser/parser.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -343,9 +343,14 @@ def p_sort_items(p):
343343

344344

345345
def p_sort_item(p):
346-
r"""sort_item : value_expression order_opt null_ordering_opt"""
347-
p[0] = SortItem(p.lineno(1), p.lexpos(1),
348-
sort_key=p[1], ordering=p[2] or 'asc', null_ordering=p[3])
346+
r"""sort_item : value_expression order_opt null_ordering_opt
347+
| LPAREN value_expression RPAREN order_opt null_ordering_opt"""
348+
if len(p) == 4:
349+
p[0] = SortItem(p.lineno(1), p.lexpos(1),
350+
sort_key=p[1], ordering=p[2] or 'asc', null_ordering=p[3])
351+
else:
352+
p[0] = SortItem(p.lineno(1), p.lexpos(1),
353+
sort_key=p[2], ordering=p[4] or 'asc', null_ordering=p[5])
349354

350355

351356
def p_order_opt(p):

test/parser/test_parser_dml.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,13 @@ def test_union_has_order_limit(self):
456456
result = oceanbase_parser.parse(sql)
457457
assert isinstance(result, Statement)
458458

459+
def test_order_by_has_parentheses(self):
460+
sql = """
461+
SELECT channel_code , contact_number FROM customer_contact_channels WHERE active_to_date - active_from_date = (SELECT active_to_date - active_from_date FROM customer_contact_channels ORDER BY (active_to_date - active_from_date) DESC LIMIT 1) """
462+
sql = Utils.remove_sql_text_affects_parser(sql)
463+
result = oceanbase_parser.parse(sql)
464+
assert isinstance(result, Statement)
465+
459466

460467
if __name__ == '__main__':
461468
unittest.main()

0 commit comments

Comments
 (0)