formatter.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. #
  2. # Copyright (C) 2009-2020 the sqlparse authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of python-sqlparse and is released under
  6. # the BSD License: https://opensource.org/licenses/BSD-3-Clause
  7. """SQL formatter"""
  8. from sqlparse import filters
  9. from sqlparse.exceptions import SQLParseError
  10. def validate_options(options):
  11. """Validates options."""
  12. kwcase = options.get('keyword_case')
  13. if kwcase not in [None, 'upper', 'lower', 'capitalize']:
  14. raise SQLParseError('Invalid value for keyword_case: '
  15. '{!r}'.format(kwcase))
  16. idcase = options.get('identifier_case')
  17. if idcase not in [None, 'upper', 'lower', 'capitalize']:
  18. raise SQLParseError('Invalid value for identifier_case: '
  19. '{!r}'.format(idcase))
  20. ofrmt = options.get('output_format')
  21. if ofrmt not in [None, 'sql', 'python', 'php']:
  22. raise SQLParseError('Unknown output format: '
  23. '{!r}'.format(ofrmt))
  24. strip_comments = options.get('strip_comments', False)
  25. if strip_comments not in [True, False]:
  26. raise SQLParseError('Invalid value for strip_comments: '
  27. '{!r}'.format(strip_comments))
  28. space_around_operators = options.get('use_space_around_operators', False)
  29. if space_around_operators not in [True, False]:
  30. raise SQLParseError('Invalid value for use_space_around_operators: '
  31. '{!r}'.format(space_around_operators))
  32. strip_ws = options.get('strip_whitespace', False)
  33. if strip_ws not in [True, False]:
  34. raise SQLParseError('Invalid value for strip_whitespace: '
  35. '{!r}'.format(strip_ws))
  36. truncate_strings = options.get('truncate_strings')
  37. if truncate_strings is not None:
  38. try:
  39. truncate_strings = int(truncate_strings)
  40. except (ValueError, TypeError):
  41. raise SQLParseError('Invalid value for truncate_strings: '
  42. '{!r}'.format(truncate_strings))
  43. if truncate_strings <= 1:
  44. raise SQLParseError('Invalid value for truncate_strings: '
  45. '{!r}'.format(truncate_strings))
  46. options['truncate_strings'] = truncate_strings
  47. options['truncate_char'] = options.get('truncate_char', '[...]')
  48. indent_columns = options.get('indent_columns', False)
  49. if indent_columns not in [True, False]:
  50. raise SQLParseError('Invalid value for indent_columns: '
  51. '{!r}'.format(indent_columns))
  52. elif indent_columns:
  53. options['reindent'] = True # enforce reindent
  54. options['indent_columns'] = indent_columns
  55. reindent = options.get('reindent', False)
  56. if reindent not in [True, False]:
  57. raise SQLParseError('Invalid value for reindent: '
  58. '{!r}'.format(reindent))
  59. elif reindent:
  60. options['strip_whitespace'] = True
  61. reindent_aligned = options.get('reindent_aligned', False)
  62. if reindent_aligned not in [True, False]:
  63. raise SQLParseError('Invalid value for reindent_aligned: '
  64. '{!r}'.format(reindent))
  65. elif reindent_aligned:
  66. options['strip_whitespace'] = True
  67. indent_after_first = options.get('indent_after_first', False)
  68. if indent_after_first not in [True, False]:
  69. raise SQLParseError('Invalid value for indent_after_first: '
  70. '{!r}'.format(indent_after_first))
  71. options['indent_after_first'] = indent_after_first
  72. indent_tabs = options.get('indent_tabs', False)
  73. if indent_tabs not in [True, False]:
  74. raise SQLParseError('Invalid value for indent_tabs: '
  75. '{!r}'.format(indent_tabs))
  76. elif indent_tabs:
  77. options['indent_char'] = '\t'
  78. else:
  79. options['indent_char'] = ' '
  80. indent_width = options.get('indent_width', 2)
  81. try:
  82. indent_width = int(indent_width)
  83. except (TypeError, ValueError):
  84. raise SQLParseError('indent_width requires an integer')
  85. if indent_width < 1:
  86. raise SQLParseError('indent_width requires a positive integer')
  87. options['indent_width'] = indent_width
  88. wrap_after = options.get('wrap_after', 0)
  89. try:
  90. wrap_after = int(wrap_after)
  91. except (TypeError, ValueError):
  92. raise SQLParseError('wrap_after requires an integer')
  93. if wrap_after < 0:
  94. raise SQLParseError('wrap_after requires a positive integer')
  95. options['wrap_after'] = wrap_after
  96. comma_first = options.get('comma_first', False)
  97. if comma_first not in [True, False]:
  98. raise SQLParseError('comma_first requires a boolean value')
  99. options['comma_first'] = comma_first
  100. right_margin = options.get('right_margin')
  101. if right_margin is not None:
  102. try:
  103. right_margin = int(right_margin)
  104. except (TypeError, ValueError):
  105. raise SQLParseError('right_margin requires an integer')
  106. if right_margin < 10:
  107. raise SQLParseError('right_margin requires an integer > 10')
  108. options['right_margin'] = right_margin
  109. return options
  110. def build_filter_stack(stack, options):
  111. """Setup and return a filter stack.
  112. Args:
  113. stack: :class:`~sqlparse.filters.FilterStack` instance
  114. options: Dictionary with options validated by validate_options.
  115. """
  116. # Token filter
  117. if options.get('keyword_case'):
  118. stack.preprocess.append(
  119. filters.KeywordCaseFilter(options['keyword_case']))
  120. if options.get('identifier_case'):
  121. stack.preprocess.append(
  122. filters.IdentifierCaseFilter(options['identifier_case']))
  123. if options.get('truncate_strings'):
  124. stack.preprocess.append(filters.TruncateStringFilter(
  125. width=options['truncate_strings'], char=options['truncate_char']))
  126. if options.get('use_space_around_operators', False):
  127. stack.enable_grouping()
  128. stack.stmtprocess.append(filters.SpacesAroundOperatorsFilter())
  129. # After grouping
  130. if options.get('strip_comments'):
  131. stack.enable_grouping()
  132. stack.stmtprocess.append(filters.StripCommentsFilter())
  133. if options.get('strip_whitespace') or options.get('reindent'):
  134. stack.enable_grouping()
  135. stack.stmtprocess.append(filters.StripWhitespaceFilter())
  136. if options.get('reindent'):
  137. stack.enable_grouping()
  138. stack.stmtprocess.append(
  139. filters.ReindentFilter(
  140. char=options['indent_char'],
  141. width=options['indent_width'],
  142. indent_after_first=options['indent_after_first'],
  143. indent_columns=options['indent_columns'],
  144. wrap_after=options['wrap_after'],
  145. comma_first=options['comma_first']))
  146. if options.get('reindent_aligned', False):
  147. stack.enable_grouping()
  148. stack.stmtprocess.append(
  149. filters.AlignedIndentFilter(char=options['indent_char']))
  150. if options.get('right_margin'):
  151. stack.enable_grouping()
  152. stack.stmtprocess.append(
  153. filters.RightMarginFilter(width=options['right_margin']))
  154. # Serializer
  155. if options.get('output_format'):
  156. frmt = options['output_format']
  157. if frmt.lower() == 'php':
  158. fltr = filters.OutputPHPFilter()
  159. elif frmt.lower() == 'python':
  160. fltr = filters.OutputPythonFilter()
  161. else:
  162. fltr = None
  163. if fltr is not None:
  164. stack.postprocess.append(fltr)
  165. return stack