__init__.py 2.4 KB

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