55# This module is part of python-sqlparse and is released under
66# the BSD License: https://opensource.org/licenses/BSD-3-Clause
77
8+ import re
9+
810from sqlparse import sql , tokens as T
911from sqlparse .utils import split_unquoted_newlines
1012
1113
1214class StripCommentsFilter :
15+
1316 @staticmethod
1417 def _process (tlist ):
1518 def get_next_comment ():
1619 # TODO(andi) Comment types should be unified, see related issue38
1720 return tlist .token_next_by (i = sql .Comment , t = T .Comment )
1821
22+ def _get_insert_token (token ):
23+ """Returns either a whitespace or the line breaks from token."""
24+ # See issue484 why line breaks should be preserved.
25+ m = re .search (r'((\r\n|\r|\n)+) *$' , token .value )
26+ if m is not None :
27+ return sql .Token (T .Whitespace .Newline , m .groups ()[0 ])
28+ else :
29+ return sql .Token (T .Whitespace , ' ' )
30+
1931 tidx , token = get_next_comment ()
2032 while token :
2133 pidx , prev_ = tlist .token_prev (tidx , skip_ws = False )
@@ -26,15 +38,12 @@ def get_next_comment():
2638 or prev_ .is_whitespace or prev_ .match (T .Punctuation , '(' )
2739 or next_ .is_whitespace or next_ .match (T .Punctuation , ')' )):
2840 # Insert a whitespace to ensure the following SQL produces
29- # a valid SQL (see #425). For example:
30- #
31- # Before: select a--comment\nfrom foo
32- # After: select a from foo
33- if prev_ is not None and next_ is None :
34- tlist .tokens .insert (tidx , sql .Token (T .Whitespace , ' ' ))
41+ # a valid SQL (see #425).
42+ if prev_ is not None and not prev_ .match (T .Punctuation , '(' ):
43+ tlist .tokens .insert (tidx , _get_insert_token (token ))
3544 tlist .tokens .remove (token )
3645 else :
37- tlist .tokens [tidx ] = sql . Token ( T . Whitespace , ' ' )
46+ tlist .tokens [tidx ] = _get_insert_token ( token )
3847
3948 tidx , token = get_next_comment ()
4049
0 commit comments