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.

__init__.py 2.2KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2018 the sqlparse authors and contributors
  4. # <see AUTHORS file>
  5. #
  6. # This module is part of python-sqlparse and is released under
  7. # the BSD License: https://opensource.org/licenses/BSD-3-Clause
  8. """Parse SQL statements."""
  9. # Setup namespace
  10. from sqlparse import sql
  11. from sqlparse import cli
  12. from sqlparse import engine
  13. from sqlparse import tokens
  14. from sqlparse import filters
  15. from sqlparse import formatter
  16. from sqlparse.compat import text_type
  17. __version__ = '0.3.0'
  18. __all__ = ['engine', 'filters', 'formatter', 'sql', 'tokens', 'cli']
  19. def parse(sql, encoding=None):
  20. """Parse sql and return a list of statements.
  21. :param sql: A string containing one or more SQL statements.
  22. :param encoding: The encoding of the statement (optional).
  23. :returns: A tuple of :class:`~sqlparse.sql.Statement` instances.
  24. """
  25. return tuple(parsestream(sql, encoding))
  26. def parsestream(stream, encoding=None):
  27. """Parses sql statements from file-like object.
  28. :param stream: A file-like object.
  29. :param encoding: The encoding of the stream contents (optional).
  30. :returns: A generator of :class:`~sqlparse.sql.Statement` instances.
  31. """
  32. stack = engine.FilterStack()
  33. stack.enable_grouping()
  34. return stack.run(stream, encoding)
  35. def format(sql, encoding=None, **options):
  36. """Format *sql* according to *options*.
  37. Available options are documented in :ref:`formatting`.
  38. In addition to the formatting options this function accepts the
  39. keyword "encoding" which determines the encoding of the statement.
  40. :returns: The formatted SQL statement as string.
  41. """
  42. stack = engine.FilterStack()
  43. options = formatter.validate_options(options)
  44. stack = formatter.build_filter_stack(stack, options)
  45. stack.postprocess.append(filters.SerializerUnicode())
  46. return u''.join(stack.run(sql, encoding))
  47. def split(sql, encoding=None):
  48. """Split *sql* into single statements.
  49. :param sql: A string containing one or more SQL statements.
  50. :param encoding: The encoding of the statement (optional).
  51. :returns: A list of strings.
  52. """
  53. stack = engine.FilterStack()
  54. return [text_type(stmt).strip() for stmt in stack.run(sql, encoding)]