Skip to content

Commit

Permalink
Ignore comments at beginning of statement when calling Statement.get_…
Browse files Browse the repository at this point in the history
…type (fixes #186).
  • Loading branch information
andialbrecht committed Jul 26, 2015
1 parent 8b5a957 commit fb6b59d
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ Bug Fixes
* sqlformat command line tool doesn't duplicat newlines anymore (issue191).
* Don't mix up MySQL comments starting with hash and MSSQL
temp tables (issue192).
* Statement.get_type() now ignores comments at the beginning of
a statement (issue186).


Release 0.1.15 (Apr 15, 2015)
Expand Down
12 changes: 10 additions & 2 deletions sqlparse/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,15 +240,20 @@ def get_sublists(self):
def _groupable_tokens(self):
return self.tokens

def token_first(self, ignore_whitespace=True):
def token_first(self, ignore_whitespace=True, ignore_comments=False):
"""Returns the first child token.
If *ignore_whitespace* is ``True`` (the default), whitespace
tokens are ignored.
if *ignore_comments* is ``True`` (default: ``False``), comments are
ignored too.
"""
for token in self.tokens:
if ignore_whitespace and token.is_whitespace():
continue
if ignore_comments and isinstance(token, Comment):
continue
return token

def token_next_by_instance(self, idx, clss):
Expand Down Expand Up @@ -468,8 +473,11 @@ def get_type(self):
The returned value is a string holding an upper-cased reprint of
the first DML or DDL keyword. If the first token in this group
isn't a DML or DDL keyword "UNKNOWN" is returned.
Whitespaces and comments at the beginning of the statement
are ignored.
"""
first_token = self.token_first()
first_token = self.token_first(ignore_comments=True)
if first_token is None:
# An "empty" statement that either has not tokens at all
# or only whitespace tokens.
Expand Down
6 changes: 6 additions & 0 deletions tests/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,9 @@ def test_issue193_splitting_function():
SELECT * FROM a.b;"""
splitted = sqlparse.split(sql)
assert len(splitted) == 2


def test_issue186_get_type():
sql = "-- comment\ninsert into foo"
p = sqlparse.parse(sql)[0]
assert p.get_type() == 'INSERT'

0 comments on commit fb6b59d

Please sign in to comment.