__init__.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. """Parse SQL statements."""
  8. # Setup namespace
  9. from sqlparse import sql
  10. from sqlparse import cli
  11. from sqlparse import engine
  12. from sqlparse import tokens
  13. from sqlparse import filters
  14. from sqlparse import formatter
  15. __version__ = '0.4.2'
  16. __all__ = ['engine', 'filters', 'formatter', 'sql', 'tokens', 'cli']
  17. def parse(sql, encoding=None):
  18. """Parse sql and return a list of statements.
  19. :param sql: A string containing one or more SQL statements.
  20. :param encoding: The encoding of the statement (optional).
  21. :returns: A tuple of :class:`~sqlparse.sql.Statement` instances.
  22. """
  23. return tuple(parsestream(sql, encoding))
  24. def parsestream(stream, encoding=None):
  25. """Parses sql statements from file-like object.
  26. :param stream: A file-like object.
  27. :param encoding: The encoding of the stream contents (optional).
  28. :returns: A generator of :class:`~sqlparse.sql.Statement` instances.
  29. """
  30. stack = engine.FilterStack()
  31. stack.enable_grouping()
  32. return stack.run(stream, encoding)
  33. def format(sql, encoding=None, **options):
  34. """Format *sql* according to *options*.
  35. Available options are documented in :ref:`formatting`.
  36. In addition to the formatting options this function accepts the
  37. keyword "encoding" which determines the encoding of the statement.
  38. :returns: The formatted SQL statement as string.
  39. """
  40. stack = engine.FilterStack()
  41. options = formatter.validate_options(options)
  42. stack = formatter.build_filter_stack(stack, options)
  43. stack.postprocess.append(filters.SerializerUnicode())
  44. return ''.join(stack.run(sql, encoding))
  45. def split(sql, encoding=None):
  46. """Split *sql* into single statements.
  47. :param sql: A string containing one or more SQL statements.
  48. :param encoding: The encoding of the statement (optional).
  49. :returns: A list of strings.
  50. """
  51. stack = engine.FilterStack()
  52. return [str(stmt).strip() for stmt in stack.run(sql, encoding)]