Skip to content

Commit fb6b59d

Browse files
committed
Ignore comments at beginning of statement when calling Statement.get_type (fixes andialbrecht#186).
1 parent 8b5a957 commit fb6b59d

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

CHANGES

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ Bug Fixes
77
* sqlformat command line tool doesn't duplicat newlines anymore (issue191).
88
* Don't mix up MySQL comments starting with hash and MSSQL
99
temp tables (issue192).
10+
* Statement.get_type() now ignores comments at the beginning of
11+
a statement (issue186).
1012

1113

1214
Release 0.1.15 (Apr 15, 2015)

sqlparse/sql.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -240,15 +240,20 @@ def get_sublists(self):
240240
def _groupable_tokens(self):
241241
return self.tokens
242242

243-
def token_first(self, ignore_whitespace=True):
243+
def token_first(self, ignore_whitespace=True, ignore_comments=False):
244244
"""Returns the first child token.
245245
246246
If *ignore_whitespace* is ``True`` (the default), whitespace
247247
tokens are ignored.
248+
249+
if *ignore_comments* is ``True`` (default: ``False``), comments are
250+
ignored too.
248251
"""
249252
for token in self.tokens:
250253
if ignore_whitespace and token.is_whitespace():
251254
continue
255+
if ignore_comments and isinstance(token, Comment):
256+
continue
252257
return token
253258

254259
def token_next_by_instance(self, idx, clss):
@@ -468,8 +473,11 @@ def get_type(self):
468473
The returned value is a string holding an upper-cased reprint of
469474
the first DML or DDL keyword. If the first token in this group
470475
isn't a DML or DDL keyword "UNKNOWN" is returned.
476+
477+
Whitespaces and comments at the beginning of the statement
478+
are ignored.
471479
"""
472-
first_token = self.token_first()
480+
first_token = self.token_first(ignore_comments=True)
473481
if first_token is None:
474482
# An "empty" statement that either has not tokens at all
475483
# or only whitespace tokens.

tests/test_regressions.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,3 +255,9 @@ def test_issue193_splitting_function():
255255
SELECT * FROM a.b;"""
256256
splitted = sqlparse.split(sql)
257257
assert len(splitted) == 2
258+
259+
260+
def test_issue186_get_type():
261+
sql = "-- comment\ninsert into foo"
262+
p = sqlparse.parse(sql)[0]
263+
assert p.get_type() == 'INSERT'

0 commit comments

Comments
 (0)