Skip to content

Commit a648aad

Browse files
committed
Errors with syntax loop.
like: with (col1, col2) as (subquery) as ..., it enters an infinite loop. return exception
1 parent 2295876 commit a648aad

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

sql_metadata/parser.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,10 @@ def _handle_with_name_save(token: SQLToken, with_names: List[str]) -> None:
668668
token.is_with_columns_end = True
669669
token.is_nested_function_end = False
670670
start_token = token.find_nearest_token("(")
671+
# like: with (col1, col2) as (subquery) as ..., it enters an infinite loop.
672+
# return exception
673+
if start_token.is_with_query_start:
674+
raise ValueError("This query is wrong")
671675
start_token.is_with_columns_start = True
672676
start_token.is_nested_function_start = False
673677
prev_token = start_token.previous_token

test/test_with_statements.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import pytest
2+
13
from sql_metadata import Parser
24
from sql_metadata.keywords_lists import QueryType
35

@@ -493,3 +495,34 @@ def test_identifier_syntax():
493495

494496
assert parser.tables == ["hits"]
495497
assert parser.columns == ["EventDate", "EventTime", "ts_upper_bound"]
498+
499+
500+
def test_as_was_preceded_by_with_query():
501+
# fix
502+
# When 'with .* as (.*) as ...', it should prompt an error instead of an infinite loop.
503+
query = """
504+
WITH
505+
t1 (c1, c2) AS (SELECT * FROM t2) AS a1
506+
SELECT 1;
507+
"""
508+
parser = Parser(query)
509+
with pytest.raises(ValueError, match="This query is wrong"):
510+
parser.tables
511+
512+
query = """
513+
WITH
514+
t1 as (SELECT * FROM t2) AS
515+
SELECT 1;
516+
"""
517+
parser = Parser(query)
518+
with pytest.raises(ValueError, match="This query is wrong"):
519+
parser.tables
520+
521+
query = """
522+
WITH
523+
'2023-01-01' as (date) AS
524+
SELECT 1;
525+
"""
526+
parser = Parser(query)
527+
with pytest.raises(ValueError, match="This query is wrong"):
528+
parser.tables

0 commit comments

Comments
 (0)