Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

formatter.py 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com
  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. '{0!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. '{0!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. '{0!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. '{0!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. '{0!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. '{0!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. '{0!r}'.format(truncate_strings))
  43. if truncate_strings <= 1:
  44. raise SQLParseError('Invalid value for truncate_strings: '
  45. '{0!r}'.format(truncate_strings))
  46. options['truncate_strings'] = truncate_strings
  47. options['truncate_char'] = options.get('truncate_char', '[...]')
  48. reindent = options.get('reindent', False)
  49. if reindent not in [True, False]:
  50. raise SQLParseError('Invalid value for reindent: '
  51. '{0!r}'.format(reindent))
  52. elif reindent:
  53. options['strip_whitespace'] = True
  54. reindent_aligned = options.get('reindent_aligned', False)
  55. if reindent_aligned not in [True, False]:
  56. raise SQLParseError('Invalid value for reindent_aligned: '
  57. '{0!r}'.format(reindent))
  58. elif reindent_aligned:
  59. options['strip_whitespace'] = True
  60. indent_tabs = options.get('indent_tabs', False)
  61. if indent_tabs not in [True, False]:
  62. raise SQLParseError('Invalid value for indent_tabs: '
  63. '{0!r}'.format(indent_tabs))
  64. elif indent_tabs:
  65. options['indent_char'] = '\t'
  66. else:
  67. options['indent_char'] = ' '
  68. indent_width = options.get('indent_width', 2)
  69. try:
  70. indent_width = int(indent_width)
  71. except (TypeError, ValueError):
  72. raise SQLParseError('indent_width requires an integer')
  73. if indent_width < 1:
  74. raise SQLParseError('indent_width requires a positive integer')
  75. options['indent_width'] = indent_width
  76. wrap_after = options.get('wrap_after', 0)
  77. try:
  78. wrap_after = int(wrap_after)
  79. except (TypeError, ValueError):
  80. raise SQLParseError('wrap_after requires an integer')
  81. if wrap_after < 0:
  82. raise SQLParseError('wrap_after requires a positive integer')
  83. options['wrap_after'] = wrap_after
  84. comma_first = options.get('comma_first', False)
  85. if comma_first not in [True, False]:
  86. raise SQLParseError('comma_first requires a boolean value')
  87. options['comma_first'] = comma_first
  88. right_margin = options.get('right_margin')
  89. if right_margin is not None:
  90. try:
  91. right_margin = int(right_margin)
  92. except (TypeError, ValueError):
  93. raise SQLParseError('right_margin requires an integer')
  94. if right_margin < 10:
  95. raise SQLParseError('right_margin requires an integer > 10')
  96. options['right_margin'] = right_margin
  97. return options
  98. def build_filter_stack(stack, options):
  99. """Setup and return a filter stack.
  100. Args:
  101. stack: :class:`~sqlparse.filters.FilterStack` instance
  102. options: Dictionary with options validated by validate_options.
  103. """
  104. # Token filter
  105. if options.get('keyword_case'):
  106. stack.preprocess.append(
  107. filters.KeywordCaseFilter(options['keyword_case']))
  108. if options.get('identifier_case'):
  109. stack.preprocess.append(
  110. filters.IdentifierCaseFilter(options['identifier_case']))
  111. if options.get('truncate_strings'):
  112. stack.preprocess.append(filters.TruncateStringFilter(
  113. width=options['truncate_strings'], char=options['truncate_char']))
  114. if options.get('use_space_around_operators', False):
  115. stack.enable_grouping()
  116. stack.stmtprocess.append(filters.SpacesAroundOperatorsFilter())
  117. # After grouping
  118. if options.get('strip_comments'):
  119. stack.enable_grouping()
  120. stack.stmtprocess.append(filters.StripCommentsFilter())
  121. if options.get('strip_whitespace') or options.get('reindent'):
  122. stack.enable_grouping()
  123. stack.stmtprocess.append(filters.StripWhitespaceFilter())
  124. if options.get('reindent'):
  125. stack.enable_grouping()
  126. stack.stmtprocess.append(
  127. filters.ReindentFilter(char=options['indent_char'],
  128. width=options['indent_width'],
  129. wrap_after=options['wrap_after'],
  130. comma_first=options['comma_first']))
  131. if options.get('reindent_aligned', False):
  132. stack.enable_grouping()
  133. stack.stmtprocess.append(
  134. filters.AlignedIndentFilter(char=options['indent_char']))
  135. if options.get('right_margin'):
  136. stack.enable_grouping()
  137. stack.stmtprocess.append(
  138. filters.RightMarginFilter(width=options['right_margin']))
  139. # Serializer
  140. if options.get('output_format'):
  141. frmt = options['output_format']
  142. if frmt.lower() == 'php':
  143. fltr = filters.OutputPHPFilter()
  144. elif frmt.lower() == 'python':
  145. fltr = filters.OutputPythonFilter()
  146. else:
  147. fltr = None
  148. if fltr is not None:
  149. stack.postprocess.append(fltr)
  150. return stack