__init__.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 typing import Any, Generator, IO, List, Optional, Tuple, Union
  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. __version__ = "0.5.5"
  17. __all__ = ["engine", "filters", "formatter", "sql", "tokens", "cli"]
  18. def parse(
  19. sql: str, encoding: Optional[str] = None
  20. ) -> Tuple[sql.Statement, ...]:
  21. """Parse sql and return a list of statements.
  22. :param sql: A string containing one or more SQL statements.
  23. :param encoding: The encoding of the statement (optional).
  24. :returns: A tuple of :class:`~sqlparse.sql.Statement` instances.
  25. """
  26. return tuple(parsestream(sql, encoding))
  27. def parsestream(
  28. stream: Union[str, IO[str]], encoding: Optional[str] = None
  29. ) -> Generator[sql.Statement, None, None]:
  30. """Parses sql statements from file-like object.
  31. :param stream: A file-like object.
  32. :param encoding: The encoding of the stream contents (optional).
  33. :returns: A generator of :class:`~sqlparse.sql.Statement` instances.
  34. """
  35. stack = engine.FilterStack()
  36. stack.enable_grouping()
  37. return stack.run(stream, encoding)
  38. def format(sql: str, encoding: Optional[str] = None, **options: Any) -> str:
  39. """Format *sql* according to *options*.
  40. Available options are documented in :ref:`formatting`.
  41. In addition to the formatting options this function accepts the
  42. keyword "encoding" which determines the encoding of the statement.
  43. :returns: The formatted SQL statement as string.
  44. """
  45. stack = engine.FilterStack()
  46. options = formatter.validate_options(options)
  47. stack = formatter.build_filter_stack(stack, options)
  48. stack.postprocess.append(filters.SerializerUnicode())
  49. return "".join(stack.run(sql, encoding))
  50. def split(
  51. sql: str, encoding: Optional[str] = None, strip_semicolon: bool = False
  52. ) -> List[str]:
  53. """Split *sql* into single statements.
  54. :param sql: A string containing one or more SQL statements.
  55. :param encoding: The encoding of the statement (optional).
  56. :param strip_semicolon: If True, remove trailing semicolons
  57. (default: False).
  58. :returns: A list of strings.
  59. """
  60. stack = engine.FilterStack(strip_semicolon=strip_semicolon)
  61. return [str(stmt).strip() for stmt in stack.run(sql, encoding)]