Skip to content

Commit dd9d5b9

Browse files
committed
Fix get_type with comments between WITH keyword
1 parent 907fb49 commit dd9d5b9

File tree

2 files changed

+23
-13
lines changed

2 files changed

+23
-13
lines changed

sqlparse/sql.py

+14-13
Original file line numberDiff line numberDiff line change
@@ -413,27 +413,28 @@ def get_type(self):
413413
Whitespaces and comments at the beginning of the statement
414414
are ignored.
415415
"""
416-
first_token = self.token_first(skip_cm=True)
417-
if first_token is None:
416+
token = self.token_first(skip_cm=True)
417+
if token is None:
418418
# An "empty" statement that either has not tokens at all
419419
# or only whitespace tokens.
420420
return 'UNKNOWN'
421421

422-
elif first_token.ttype in (T.Keyword.DML, T.Keyword.DDL):
423-
return first_token.normalized
422+
elif token.ttype in (T.Keyword.DML, T.Keyword.DDL):
423+
return token.normalized
424424

425-
elif first_token.ttype == T.Keyword.CTE:
425+
elif token.ttype == T.Keyword.CTE:
426426
# The WITH keyword should be followed by either an Identifier or
427427
# an IdentifierList containing the CTE definitions; the actual
428428
# DML keyword (e.g. SELECT, INSERT) will follow next.
429-
fidx = self.token_index(first_token)
430-
tidx, token = self.token_next(fidx, skip_ws=True)
431-
if isinstance(token, (Identifier, IdentifierList)):
432-
_, dml_keyword = self.token_next(tidx, skip_ws=True)
433-
434-
if dml_keyword is not None \
435-
and dml_keyword.ttype == T.Keyword.DML:
436-
return dml_keyword.normalized
429+
tidx = self.token_index(token)
430+
while tidx is not None:
431+
tidx, token = self.token_next(tidx, skip_ws=True)
432+
if isinstance(token, (Identifier, IdentifierList)):
433+
tidx, token = self.token_next(tidx, skip_ws=True)
434+
435+
if token is not None \
436+
and token.ttype == T.Keyword.DML:
437+
return token.normalized
437438

438439
# Hmm, probably invalid syntax, so return unknown.
439440
return 'UNKNOWN'

tests/test_regressions.py

+9
Original file line numberDiff line numberDiff line change
@@ -427,3 +427,12 @@ def test_splitting_at_and_backticks_issue588():
427427
'grant foo to user1@`myhost`; grant bar to user1@`myhost`;')
428428
assert len(splitted) == 2
429429
assert splitted[-1] == 'grant bar to user1@`myhost`;'
430+
431+
432+
def test_comment_between_cte_clauses_issue632():
433+
p, = sqlparse.parse("""
434+
WITH foo AS (),
435+
-- A comment before baz subquery
436+
baz AS ()
437+
SELECT * FROM baz;""")
438+
assert p.get_type() == "SELECT"

0 commit comments

Comments
 (0)