Advertisement
lichenran1234

removeSqlComments

Apr 15th, 2021
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. def removeSqlComments(source):
  2.     result = []
  3.    
  4.     state = 0
  5.     # states:
  6.     # 0 - initial state
  7.     # 1 - have single '-'
  8.     # 2 - have double '-' (valid comment)
  9.     # 3 - have single "'"
  10.     # 4 - have single '\' inside quotes
  11.     for char in source:
  12.         result.append(char)
  13.         if state == 0:
  14.             if char == '-':
  15.                 state = 1
  16.             elif char == "'":
  17.                 state = 3
  18.             else:
  19.                 state = 0
  20.         elif state == 1:
  21.             if char == '-':
  22.                 state = 2
  23.                 result.pop()
  24.                 result.pop()
  25.             else:
  26.                 state = 0
  27.         elif state == 2:
  28.             if char == '\n':
  29.                 state = 0
  30.             else:
  31.                 result.pop()
  32.                 state = 2
  33.         elif state == 3:
  34.             if char == '\\':
  35.                 state = 4
  36.             elif char == "'":
  37.                 state = 0
  38.             else:
  39.                 state = 3
  40.         elif state == 4:
  41.             state = 3
  42.    
  43.     print ''.join(result)
  44.    
  45. test1 = r"""
  46. SELECT * FROM Students -- here's comment1
  47. WHERE age > 20 and name like 'A%\\'--start of a comment'; -- also comment
  48. """
  49.  
  50. removeSqlComments(test1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement